标签搜索

目 录CONTENT

文章目录

【算法模板】栈式中序遍历

陈铭
2022-05-16 / 0 评论 / 1 点赞 / 180 阅读 / 251 字 / 正在检测是否收录...

例题:后继者

力扣面试题 04.06题为例:

设计一个算法,找出二叉搜索树中指定节点的“下一个”节点(也即中序后继)。
如果指定节点没有对应的“下一个”节点,则返回null。
本题题意理解: 在二叉搜索树中找到大于节点 p 的值中的所有节点值最小的一个节点。即中序遍历整个树(从小到大),找到毗邻节点p的下一个节点。

class Solution {
    public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
        // ArrayDeque可以当作队列,也可以当作栈使用
		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;
			// 如果是遍历
			// 去掉这几句
			// if (prev == p) {
            //     return curr;
            // }
			// prev = curr;
			// 把curr记录到数组中,就是在中序遍历了
			// 即:add(curr);
            curr = curr.right;
        }
        return null;
    }
}
1

评论区