给定一棵二叉树的其中一个节点,请找出中序遍历序列的下一个节点。
注意:
- 如果给定的节点是中序遍历序列的最后一个,则返回空节点;
- 二叉树一定不为空,且给定的节点一定不是空节点;
数据范围
树中节点数量 [0,100]。
样例
假定二叉树是:[2, 1, 3, null, null, null, null], 给出的是值等于2的节点。
则应返回值等于3的节点。
解释:该二叉树的结构如下,2的后继节点是3。
2
/ \
1 3
题解:
题目给出的为中序遍历,则目标结点的后继有两种情况
1、该结点有右孩子,则后继为右子树中最左的结点
2、该结点无右孩子,若存在一个祖先结点是自身父结点的左孩子,则后继为这个父结点;
反之为空
/**
* 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.right!=null){
p = p.right;
while(p.left != null){
p = p.left;
}
return p;
}
//无右孩子,找到一个祖先结点,该结点为自身父节点的左孩子
else{
while(p.father != null && p.father.left != p){
p = p.father;
}
return p.father;
}
}
}