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

}

总结

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

相关推荐
小雨下雨的雨几秒前
Flutter跨平台开发实战:鸿蒙系列-循环交互艺术系列——瀑布流:不规则网格的循环排布算法
算法·flutter·华为·交互·harmonyos·鸿蒙系统
小雨下雨的雨2 分钟前
Flutter跨平台开发实战: 鸿蒙与循环交互艺术:跑马灯的无极滚动算法
算法·flutter·华为·交互·harmonyos·鸿蒙
NAGNIP8 小时前
一文搞懂机器学习中的特征降维!
算法·面试
NAGNIP8 小时前
一文搞懂机器学习中的特征构造!
算法·面试
Learn Beyond Limits9 小时前
解构语义:从词向量到神经分类|Decoding Semantics: Word Vectors and Neural Classification
人工智能·算法·机器学习·ai·分类·数据挖掘·nlp
你怎么知道我是队长9 小时前
C语言---typedef
c语言·c++·算法
Qhumaing10 小时前
C++学习:【PTA】数据结构 7-1 实验7-1(最小生成树-Prim算法)
c++·学习·算法
踩坑记录12 小时前
leetcode hot100 3.无重复字符的最长子串 medium 滑动窗口(双指针)
python·leetcode
Z1Jxxx12 小时前
01序列01序列
开发语言·c++·算法