Article Directory
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:
- 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
2
node, the next node is a3
node) - 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
1
node, the next node is a2
node) - 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
3
node, down A node is4
), there is no such parent node, there is no next node (such as9
node)
- The node is the left child of the parent node, then the next node is its parent node (such as a
/**
* 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;
}
}