Sword refers to Offer-54-the next node of the binary tree

Title description

Given a binary tree and one of its nodes, 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.

Ideas

I have always understood the meaning of next in this topic and where does it point? Later, after reading other people's analysis, I understood. Next points to the parent node.
The following solution is not original:
Link: https://www.nowcoder.com/questionTerminal/9023a0c988684a53960365b889ceaf5e?f=discussion
Source: Niuke.com
Insert picture description here

  • Analyzing the next node of the binary tree, there are the following situations:
  • 1. If the binary tree is empty, return empty;
  • 2. The right child nodes exist, a pointer is provided from the right child node, the last leaf node has to find a pointer to the left along the sub-node is the next node;
    node 2 is started from the assumption, 也就是说此时的中序遍历到了2这个节点。然后需要输出下一个节点. The right child exists as 5, so start looking for his left child from 5. Then 3 is found, 3 has no left child, and 3 is returned. This means that 2 traversal in the middle order traversal, the next traversal output should be 3.
  • 3. The node is not the root node. If the node is the left child of its parent node, return the parent node; otherwise, continue to traverse the parent node of its parent node, repeat the previous judgment, and return the result.
    Then we traversed to 3 at this time above. Then the node is the root node, the right child is 4, and there are no other nodes, it outputs 4, and then 4 is not the root node, it returns its parent node to 3, because 3 has been traversed at this time, it continues to return to it Parent node 5.

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;
        TreeLinkNode res;
        if(pNode.right == null){
    
    
            //如果此时的结点没有右节点
            res = pNode;
            while(res.next != null && res.next.right == res){
    
    
                //如果此时的节点不是作为自己的父节点的右节点,就一直向上遍历
                res = res.next;
            }
            return res.next;
        }
    //如果此时的结点存在右节点,就一直沿着遍历其左结点,知道左节点为空,此时的节点就是下一个节点
        res = pNode.right;
        while(res.left != null){
    
    
            res = res.left;
        }
        return res;
    }
}

Guess you like

Origin blog.csdn.net/H1517043456/article/details/107514466