/**
* 劍指offer書中:二叉樹的下一個節點
* 1.若當前結點有右子樹時,其下一個結點爲右子樹中最左子結點;
* 2.若當前結點無右子樹時,
* (1)若當前結點爲其父結點的左子結點時,其下一個結點爲其父結點;
* (2)若當前結點爲其父結點的右子結點時,繼續向上遍歷父結點的父結點,
* 直到找到一個結點是其父結點的左子結點(與(1)中判斷相同),該結點即爲下一結點。
* @Description
*/
public class Test06 {
//樹的節點比較特殊,除了指向左右子樹的節點外,還包含一個指向父節點的指針
class TreeLinkNode{
int value;
TreeLinkNode left;
TreeLinkNode right;
TreeLinkNode parent;
public TreeLinkNode(int value){
this.value = value;
}
}
public TreeLinkNode getNext(TreeLinkNode root){
if (root == null) return null;
//分析的第一種情況
if (root.right != null){
root = root.right;
while (root.left != null){
root = root.left;
}
return root;
}
//分析的第二種情況
while (root.parent != null){
if (root == root.parent.left){
return root.parent;
}
root = root.parent;
}
return null;
}
}
劍指Offer-05-二叉樹的下一個節點
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.