8. The next node of the binary tree

Sword refers to the next node of the offer 08 binary tree

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.

public class TreeLinkNode {
    
    
    int val;
    TreeLinkNode left = null;
    TreeLinkNode right = null;
    TreeLinkNode next = null; // 指向父结点的指针

    TreeLinkNode(int val) {
    
    
        this.val = val;
    }
}

Problem-solving ideas: thinking based on the characteristics of middle-order traversal

Suppose the binary tree is as shown in the figure below:
Insert picture description here

  1. If the node has a right child, the next node is the leftmost node in the left subtree of its right child (such as a 2node, the next node is a 3node)
  2. The node has no right child
    • The node is the left child of the parent node, then the next node is its parent node (such as a 1node, the next node is a 2node)
    • If the node is the right child of the parent node, then keep going up to find the parent node until the parent node is the left child of the parent node’s parent node, then the next node is the parent node of the parent node (such as 3node, down A node is 4), there is no such parent node, there is no next node (such as 9node)
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode father;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    
    
    public TreeNode inorderSuccessor(TreeNode p) {
    
    
        if(p==null) return null;

        if(p.right!=null){
    
    //该节点有右孩子
            p = p.right;
            while(p.left!=null){
    
    
                p = p.left;
            }
           return p;
        }  
         //该节点是父节点的左孩子
        if(p.father!=null && p.father.left == p) {
    
    
            return p.father;
        }  
       //该节点是父节点的右孩子
        while(p.father!=null && p.father.right == p){
    
    
            p = p.father;
        }
        return p.father;
    }
}

Insert picture description here

Guess you like

Origin blog.csdn.net/YouMing_Li/article/details/114253918