Offer-8 wins the next node of the binary tree
Title:
Given a binary tree and a node which is, find the next node in a preorder traversal order and returns. Note that the node in the tree contains not only the left and right child nodes, the parent node contains a pointer pointing to.
Ideas:
- The right side nodes, direct printing
- No node on the right side
- Left parent node of this node is own print
- Right parent node of this node is yourself, keep looking up, until the meet 2.1
Own answer:
/*
public class TreeLinkNode {
int val;
TreeLinkNode left = null;
TreeLinkNode right = null;
TreeLinkNode next = null;
TreeLinkNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public TreeLinkNode GetNext(TreeLinkNode pNode)
{
if(pNode == null) return null;
TreeLinkNode next = null;
if(pNode.right != null){
TreeLinkNode pRight = pNode.right;
while(pRight.left != null)
pRight = pRight.left;
next = pRight;
}else if(pNode.next != null){
TreeLinkNode curNode = pNode;
TreeLinkNode pParrent = pNode.next;
while(pParrent != null && pParrent.right == curNode){
curNode = pParrent;
pParrent = pParrent.next;
}
next = pParrent;
}
return next;
}
}
Mistakes:
note:
Someone to answer: