(Java refers to offer) the next node of the binary tree

1. Question analysis

Given a binary tree and one of its nodes, please find the next node in the in-order traversal sequence and return. Note that the nodes in the tree not only include left and right child nodes, but also pointers to parent nodes.

There are three situations in this question

(1) If the right child of the node exists, set a pointer to start from the right child of the node and find the leftmost node of the right child.
(2) If the right child does not exist, determine whether there is a parent node; if the node is the left child node of the parent node, return to the parent node directly, otherwise continue to traverse the parent node of its parent node, and determine whether the traversed node is in turn Is the left child node of the parent node.
(3) In other cases, return to empty.

Second, the code

public class Solution {
    
    
    public TreeLinkNode GetNext(TreeLinkNode pNode)
    {
    
    
        //右孩子节点存在,则从右孩子节点开始找到最左结点
        if(pNode.right!=null){
    
    
            TreeLinkNode node = pNode.right;
            while(node.left!=null){
    
    
                node=node.left;
            }
            return node;
        }else if(pNode.right==null&&pNode.next!=null){
    
    
            //不存在右孩子节点,存在父节点
            TreeLinkNode node = pNode.next;
            while(node!=null){
    
    
                //判断该节点是否是父节点的左孩子
                if(node.left==pNode)
                    return node;
                pNode=node;
                node = node.next;
            }
        }
        return null;
    }
}

Three, summary

Note that in the second case, you need to determine the parent node of the node and its relationship in turn, Just return when the conditions are met.

Guess you like

Origin blog.csdn.net/nanhuaibeian/article/details/108616997