Find the next node of the binary tree-java

topic:

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.

Problem-solving ideas:

First, display the results of the in-order traversal.
Insert picture description here
—Root left and right The result after the middle order traversal is: DNH B IEJ A FK C LGM

From this result, analyze the next node after the in-order traversal:
1. If the binary tree is empty, return empty;

2. There is a right subtree:
the next node is the leftmost node of the right subtree, and the leftmost node of the right subtree of the current node is searched all the way down.

3. There is no right subtree cases: two cases
Case 1:
The current node is the left child of the parent node , the next node is its parent;
Case 2:
the current node is the right child of its parent node, To find its next node, you must always look for the parent node of the parent node of its current node, until the current node is the left child of its parent node (may be a little bit around, you can draw a few nodes only right In the case of the child, observe how it traverses to its next node). If it is not found, it means that the current node is the tail node .
(The graph of case two: the next node of G is C)
Insert picture description here

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){
    
    
            if(pNode.next.left==pNode){
    
    
                return pNode.next;
            }
            pNode=pNode.next;
        }
        return null;//到了根节点,都还没有找到,则返回null
        
    }
}

Guess you like

Origin blog.csdn.net/m0_46551861/article/details/115199424