問題描述
給定一個二叉樹和其中的一個結點,請找出中序遍歷順序的下一個結點並且返回。注意,樹中的結點不僅包含左右子結點,同時包含指向父結點的指針。
思路
二叉樹中序遍歷的下一個結點,意思就是根據左中右來看的。如果這個結點有右子樹,則答案肯定是右子樹的最左下結點。 如果沒有右子樹,則要去看父親。如果它是父親的左孩子,則是答案,因爲左中右嘛。 如果是父親的右孩子,則去找父親的父親,因爲左中右,它是父親的右孩子,證明它的父親也被遍歷完了,只能繼續網上找。
這題用next存儲父親真的是夠走心的,呵呵。
方法一
class Solution {
public TreeLinkNode GetNext(TreeLinkNode pNode) {
if(pNode == null) return null;
TreeLinkNode res = findRightChild(pNode.right);
if(res == null){
return findParent(pNode);
}
return res;
}
private TreeLinkNode findRightChild(TreeLinkNode root){
if(root == null) return null;
while(root.left != null) root = root.left;
return root;
}
private TreeLinkNode findParent(TreeLinkNode root){
while(root.next != null){
if(root.next.left == root) return root.next;
root = root.next;
}
return null;
}
}