2014-02-21 29 views
0

我想指向二叉樹中左子樹中最右邊的節點。我正在使用java。我不斷收到空指針異常。並且root.lchild不爲null,即使對於具有3個級別的樹,我也一直得到空值 以下是我的代碼;左子樹中最右邊的節點Java

Node rightmost; 
rightmost=root.lchild; 
while(rightmost.right!=null) 
     { 
     rightmost=rightmost.right; 
     } 
+0

您也應該檢查是否'rightmost.right'不是'null'之前爲它分配。 –

+1

1.'root'可以是'null'; 2.'root.lchild'可以是'null'。 – dasblinkenlight

+0

編輯完成後,您應該沒有問題(假設您的狀態下'root.lchild'不是'null')。 –

回答

1

應該

Node rightmost = root != null ? root.lchild : null; 
if (rightmost != null) 
    while (rightmost.right != null) { 
     rightmost = rightmost.right; 
    } 
} 

if (rightmost != null) { // root or root.lchild is null 
    // found 
} 
+0

是的,我也嘗試過。但是這不是指向最右邊節點的正確孩子,而是指向最右邊的孩子本身嗎? – nitinsh99

+0

如果'rightmost'的值總是不同於'null',那麼'while'循環將是無限的。否則,如果在某個時候它是'空',那麼下一個'if'語句根本就沒有意義... –

+0

@Luiggi Mendoza現在還好嗎? – Vitaly

相關問題