59. The next node binary tree

Subject description:

  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.

Analysis of ideas:

  The next node binary tree, a total of the following circumstances:

  1. binary tree is empty, return empty

  2. The right child node exists, a pointer is set right child of view, the leaf nodes have been found along the left child node is the pointer to the next node.

  3. The node is not the root, if the left child node of the parent node, the parent node is the next node, or continue to go up the parent node of its parent node, before the judge repeated, returns the result.

Code:

/*
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;
        if(pNode.right!=null){    //右孩子不为空,从右孩子开始,沿着左指针遍历到叶子节点,即为下一个节点
            pNode=pNode.right;
            while(pNode.left!=null){
                pNode=pNode.left;
            }
            return pNode;
        }
        while(pNode.next!=null){    //pNode不为根节点
            TreeLinkNode parentNode=pNode.next;
            if(parentNode.left==pNode) //如果当前节点时父节点的左孩子,那么下一个节点就是父节点。
                return parentNode;
            pNode=pNode.next;
        }
        return null;
    }
}

Guess you like

Origin www.cnblogs.com/yjxyy/p/10961235.html