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

}

总结

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

相关推荐
Tongsr35 分钟前
别只混淆代码:用 Kaleido 加固整个 Android Release AAB
前端·算法·github
高亦真36 分钟前
今天是学习嵌入式的第34天
linux·学习·算法
飞Link2 小时前
动作方法中的分割与过度分割方法全解析(含代码实战与踩坑案例)
人工智能·python·算法·计算机视觉
张宇Joaquin2 小时前
鲲鹏统一并行加速库KUPL--异步数据拷贝
线性代数·算法·矩阵·numpy
GlobalInfo2 小时前
创新不是追逐热点,是在变化中建立长期竞争力
大数据·算法
lvwangshu2 小时前
线性代数基础 Linear Algebra Basics
数学·算法
ZhouDevin3 小时前
算法论文/数据集5——AlignPrune(CVPR2026)基于样本损失时间序列精确识别噪声样本
算法
十铭忘4 小时前
HMM(隐马尔可夫模型)的理解7——Baum–Welch 算法
人工智能·算法
明月_清风4 小时前
十大经典排序算法 Go 实现全解:从入门到面试通关
后端·算法·排序算法
liliangcsdn4 小时前
如何对IC时间序列进行汇总统计分析示例
人工智能·算法·机器学习