Offer to prove safety fifty-seven: binary tree to the next node

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 :

   5     6
 1  3   4 7

1, the next node is the next node is about 5,9 2,3 nodes is 9.


Since we know a pointer to the parent node, you can perform a detailed analysis.

  1. 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.
  2. 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.
  3. 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.
  4. 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.


public class Solution {
    public TreeLinkNode GetNext(TreeLinkNode pNode)
        TreeLinkNode head=pNode;
        if(head==null) return null;
            TreeLinkNode p=head.right;
            return p;
            if( return;
        return null;

Published 84 original articles · won praise 53 · views 7387

Guess you like