8, the next node in the binary tree

After a lapse of several days without making questions, look at this a question today.

And wherein a given binary tree of a node, find inorder traversal order the next node 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.
 
Node structure as follows:

public class TreeLinkNode {
  int val;
  TreeLinkNode left = null;
  TreeLinkNode right = null;
  TreeLinkNode next = null;

  TreeLinkNode(int val) {
  this.val = val;
  }
}

analyse as below:

(1) If there is a right child node, the next node of the points is the leftmost child node of the right subtree.

Analysis of a next node is not the right subtree of the case, if the node does not have the right subtree, then:

(1) when the node is the left child node to its parent node, then its next node is its parent node;

(2) When this node is the right child of its parent node, this situation is more complex, we need to keep up the pointer to traverse the parent node until it finds a nodes left child of its parent node (found If this node left child of its parent node). If no such node, the current node is the last node in order traversal.

public class Solution {

    public TreeLinkNode GetNext(TreeLinkNode pNode)
    {   
        IF (• pNode == null )
             return  null ;
         // current right child of a given node is not empty 
        IF (! pNode.right = null ) {
            pNode = pNode.right;
            while(pNode.left != null){
                pNode = pNode.left;
            }
            return pNode;
        }
        // The following is the right child node is empty case
         // parent node is not empty 
        the while (pNode.next! = Null )
        {    
            // If the current node is a child of the parent node, the parent node is the next node of the current node 
            IF (pNode.next.left == • pNode)
                 return pNode.next;
            pNode = pNode.next;
        }
        return null;
    }
}

 

 

 

Guess you like

Origin www.cnblogs.com/Aug-20/p/11774140.html