7 offer a second forum prove safety questions: the next node binary tree (JAVA version)

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.

Analysis:
According to preorder features, to find the next of a node is nothing more than three cases:
1, have the right subtree, then just put it right child as the next traversal (not looking) node, then the node along the left subtree (if any) set out, until it encounters a leaf node, then the leaf node is looking for its next node;
2, there is no right subtree, it is determined whether the node is the left child of its parent node, if it is looking for the next node is the parent node;
3, as the next node traversal if not left child of its parent node, put the parent node, back up until find the node has no parent or child node is left up to the parent node.
Combination of these three cases can be found next to any node in a binary tree node.

code show as below:

public  class FindNextNode {
     public BinaryTreeNode getNextNode (BinaryTreeNode • pNode) {
         IF (• pNode == null ) {
             return  null ; 
        } 
        // If the node has the right node 
        IF (! pNode.getRightNode () = null ) { 
            BinaryTreeNode tempNode, = pNode.getRightNode ();
             the while (! tempNode.getLeftNode () = null ) { 
                tempNode, = tempNode.getLeftNode (); 
            } 
            return tempNode,; 
        } 
        // if there is no right node is the left child of the parent node
        IF (pNode.getFatherNode () == null ) {
             return  null ; 
        } 
        IF (. pNode.getFatherNode () getLeftNode () == • pNode) {
             return pNode.getFatherNode (); 
        } 
        
        // if there is no right node, its parent the right child node, the parent node has been looking up until there is no parent node 
        IF (pNode.getFatherNode () == null ) {
             return  null ; 
        } 
        IF (. pNode.getFatherNode () getRightNode () == • pNode) { 
            BinaryTreeNode tempNode, = pNode.getFatherNode ();
             the while (tempNode.getFatherNode () == null){
                tempNode=tempNode.getFatherNode();
            }
            return tempNode;
        }
        return null;
    }
}

 

Guess you like

Origin www.cnblogs.com/xhlwjy/p/11258979.html