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);
	}

}

总结

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

相关推荐
yaoh.wang6 小时前
力扣(LeetCode) 13: 罗马数字转整数 - 解法思路
python·程序人生·算法·leetcode·面试·职场和发展·跳槽
T1ssy7 小时前
布隆过滤器:用概率换空间的奇妙数据结构
算法·哈希算法
hetao17338377 小时前
2025-12-12~14 hetao1733837的刷题笔记
数据结构·c++·笔记·算法
鲨莎分不晴8 小时前
强化学习第五课 —— A2C & A3C:并行化是如何杀死经验回放
网络·算法·机器学习
搞科研的小刘选手9 小时前
【ISSN/ISBN双刊号】第三届电力电子与人工智能国际学术会议(PEAI 2026)
图像处理·人工智能·算法·电力电子·学术会议
拉姆哥的小屋9 小时前
从混沌到秩序:条件扩散模型在图像转换中的哲学与技术革命
人工智能·算法·机器学习
Sammyyyyy9 小时前
DeepSeek v3.2 正式发布,对标 GPT-5
开发语言·人工智能·gpt·算法·servbay
sin_hielo10 小时前
leetcode 2110
数据结构·算法·leetcode
Jay200211110 小时前
【机器学习】33 强化学习 - 连续状态空间(DQN算法)
人工智能·算法·机器学习
铭哥的编程日记10 小时前
后端面试通关笔记:从真题到思路(五)
面试·职场和发展