The next node binary tree - prove safety offer

Title 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.
 
A thought: Xianxiang found on the node and then with preorder
public class Solution {
        boolean flag=false;
    TreeLinkNode result=null;
    public TreeLinkNode GetNext(TreeLinkNode pNode)
    {
        if(pNode == null) return null;
        TreeLinkNode head=pNode;
        while(head.next != null){
            head=head.next;
        }
        midOrder(head,pNode);
        return result;
    }

    private void midOrder(TreeLinkNode tree, TreeLinkNode pNode) {
        if(tree.left != null){
            midOrder(tree.left,pNode);
        }
        if(flag && result ==null) {//判断result==null非常重要 防止上层修改result的值
            result=tree;
            return ;
        }
        if(tree.val == pNode.val &&tree.left == pNode.left && tree.right==pNode.right && tree.next==pNode.next){
            flag=true;
        }
        if(tree.right != null){
            midOrder(tree.right,pNode);
        }
    }
}

Thinking two:

Links: https://www.nowcoder.com/questionTerminal/9023a0c988684a53960365b889ceaf5e
Source: Cattle customer network

can be divided into two categories: 1, has the right subtree, then the next node is the left-most point the right subtree; 2, no right subtree, may be divided into two types, a) is the left child node of the parent (eg: N, I, L ), then the parent node is a next node; b) is the right child of the parent node (eg: H, J, K, M) looking for his parent parent parent node ... until the current node is the left child of its parent location. If there is no eg: M, he is the tail node.

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;
        }
        TreeLinkNode tem=pNode;
        while(pNode.next != null){
            pNode=pNode.next;
            if(pNode.left == tem){
                return pNode;
            }
            tem=pNode;
        }
        return  null;
    }

}

 

 

Guess you like

Origin www.cnblogs.com/nlw-blog/p/12466748.html