題目
在二叉樹中找到一個節點的後繼節點
【題目】 現在有一種新的二叉樹節點類型如下:
public class Node { public int value; public Node left;
public Node right; public Node parent;
public Node(int data) { this.value = data; }
}
該結構比普通二叉樹節點結構多了一個指向父節點的parent指針。假
設有一 棵Node類型的節點組成的二叉樹,樹中每個節點的parent指針
都正確地指向 自己的父節點,頭節點的parent指向null。只給一個在
二叉樹中的某個節點 node,請實現返回node的後繼節點的函數。在二
叉樹的中序遍歷的序列中, node的下一個節點叫作node的後繼節點。
思路
實現思路:
a.如果一個節點有右子樹,後繼節點就是當前節點右子樹的最左節點。
b.如果一個節點沒有右子樹,後繼節點就是向上尋找的節點 是其父節點的左子樹
code
public static class Node {
public int value;
public Node left;
public Node right;
public Node parent;
public Node(int data) {
this.value = data;
}
}
public Node findLastNode(Node head){
if (head == null) {
return null;
}
//查找當前節點有沒有有子樹 如果有 右子樹的最左節點就是後繼節點。
if (head.right!=null){
return findLeftNode(head.right);
}else{
//當前節點沒有右子樹 向上查找當前節點如果父節點的左子節點等於它 那麼他就是後繼節點
Node parent = head.parent;
while (parent!=null && parent.left!=head){
head = parent;
parent = head.parent;
}
return parent;
}
}
public Node findLeftNode(Node node){
if (node!=null){
while (node!=null){
node = node.left;
}
return node;
}
return null;
}