LeetCode面试题 04.06 后继者

题目

解答一

java 复制代码
class Solution {
	List<TreeNode> nodes = new ArrayList<>();

	public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
		inorder(root);
		int index = -1;
		for (int i = 0; i < nodes.size(); ++i) {
			TreeNode node = nodes.get(i);
			if (node.val == p.val) {
				index = i;
				break;
			}
		}

		if (index == -1) {
			return null;
		}

		if (index == nodes.size() - 1) {
			return null;
		}

		return nodes.get(index + 1);
	}

	void inorder(TreeNode root) {
		if (root == null) {
			return;
		}

		inorder(root.left);
		nodes.add(root);
		inorder(root.right);
	}

}

解答二

java 复制代码
class Solution {
	List<TreeNode> nodes = new LinkedList<>();

	public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
		inorder(root, p);
		if (nodes.isEmpty()) {
			return null;
		}
		
		nodes.removeFirst();
		if (nodes.isEmpty()) {
			return null;
		}
		return nodes.removeFirst();
	}

	void inorder(TreeNode root, TreeNode p) {
		if (root == null) {
			return;
		}

		inorder(root.left, p);
		if (root.val >= p.val) {
			nodes.add(root);
		}
		inorder(root.right, p);
	}

}

总结

利用二叉搜索树的特征,中序遍历时为升序排列的结果。

相关推荐
AI软著研究员5 小时前
程序员必看:软著不是“面子工程”,是代码的“法律保险”
算法
FunnySaltyFish5 小时前
什么?Compose 把 GapBuffer 换成了 LinkBuffer?
算法·kotlin·android jetpack
颜酱6 小时前
理解二叉树最近公共祖先(LCA):从基础到变种解析
javascript·后端·算法
地平线开发者1 天前
SparseDrive 模型导出与性能优化实战
算法·自动驾驶
董董灿是个攻城狮1 天前
大模型连载2:初步认识 tokenizer 的过程
算法
地平线开发者1 天前
地平线 VP 接口工程实践(一):hbVPRoiResize 接口功能、使用约束与典型问题总结
算法·自动驾驶
罗西的思考1 天前
AI Agent框架探秘:拆解 OpenHands(10)--- Runtime
人工智能·算法·机器学习
HXhlx1 天前
CART决策树基本原理
算法·机器学习
Wect1 天前
LeetCode 210. 课程表 II 题解:Kahn算法+DFS 双解法精讲
前端·算法·typescript
颜酱1 天前
单调队列:滑动窗口极值问题的最优解(通用模板版)
javascript·后端·算法