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

}

总结

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

相关推荐
IT·小灰灰1 小时前
基于Python的机器学习/数据分析环境搭建完全指南
开发语言·人工智能·python·算法·机器学习·数据分析
wefg12 小时前
【C++】智能指针
开发语言·c++·算法
搂鱼1145142 小时前
一类判断包含颜色整体的题目
算法
Demon--hx2 小时前
[c++]string的三种遍历方式
开发语言·c++·算法
无敌最俊朗@2 小时前
力扣hot100 - 合并两个有序链表21
算法·leetcode·链表
墨染点香2 小时前
LeetCode 刷题【168. Excel 表列名称】
算法·leetcode·职场和发展
hans汉斯2 小时前
基于改进YOLOv11n的无人机红外目标检测算法
大数据·数据库·人工智能·算法·yolo·目标检测·无人机
Swift社区3 小时前
LeetCode 431 - 将 N 叉树编码成二叉树
算法·leetcode·职场和发展
子豪-中国机器人3 小时前
1030-csp 2019 入门级第一轮
算法