Casual working
And wherein a given binary tree of a node, 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.
For chestnut :
2
5 6
1 3 4 7
9
1, the next node is the next node is about 5,9 2,3 nodes is 9.
Thinking
Since we know a pointer to the parent node, you can perform a detailed analysis.
- For no sibling nodes, and a left subtree of the parent node, when, for example 1, which is the next node is its parent node.
- For left and right sub-tree or sub-tree node has the right, the left and right sub-tree no sub-tree. 3 and 5, for example, that the next node is its right child.
- For no left node and a right subtree when the parent node would need to check up query to the left subtree of the parent node of a node is its own, such as 5, this time, the next node 9 is 5 father.
- For right subtree and the right subtree when the left subtree, recursively to the bottom left subtree of a node, such as the next 2 is 4.
Code
public class Solution {
public TreeLinkNode GetNext(TreeLinkNode pNode)
{
TreeLinkNode head=pNode;
if(head==null) return null;
if(head.right!=null)
{
TreeLinkNode p=head.right;
while(p.left!=null)
p=p.left;
return p;
}
while(head.next!=null){
if(head.next.left==head) return head.next;
head=head.next;
}
return null;
}
}