【力扣面试】面试题 04.06. 后继者
题目
设计一个算法,找出二叉搜索树中指定节点的“下一个”节点(也即中序后继)。
如果指定节点没有对应的“下一个”节点,则返回null。
示例 1:
示例 2:
解题思路
思路:
1、题目就是求二叉树中序遍历后的某个结点的后继结点
2、利用递归版的中序遍历,List res 存储中序遍历结点结果
3、若要指定的节点为最后一个节点,那么其后继必然是null,否则就是该节点的next
代码
class Solution {
public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
List<TreeNode> res = new ArrayList<>();
inorder(root, res);
int flag = 0;
for (int i = 0; i < res.size(); i++) {
if (res.get(i) == p) {
flag = i;
break;
}
}
if (flag + 1 < res.size()) {
return res.get(flag + 1);
}else {
return null;
}
}
public void inorder(TreeNode root, List<TreeNode> res) {
if (root == null) {
return;
}
inorder(root.left, res);
res.add(root);
inorder(root.right, res);
}
}