题目描述
思路
题目很明显是需要中序遍历,这里需要找到中序遍历中,指定节点的后继节点(中序遍历的顺序是:左根右),即,可能会存在寻找左子节点的父节点情况,这里,最简单容易想到的是双指针+中序遍历非递归,其中一个指针用来遍历,另一个指针则指向当前遍历节点的上一个节点
代码
class Solution {
public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
Deque<TreeNode> stack = new ArrayDeque<TreeNode>();
TreeNode prev = null, curr = root;
while (!stack.isEmpty() || curr != null) {
while (curr != null) {
stack.push(curr);
curr = curr.left;
}
curr = stack.pop();
if (prev == p) {
return curr;
}
prev = curr;
curr = curr.right;
}
return null;
}
}
|