二叉树公共父节点专题
BST,二叉搜索树的公共父节点
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/
给定一个二叉搜索树root, 另外两个二叉搜索树p,q,求p和q的最小公共父节点。注意p可以是p自己的父节点
解析
充分利用二叉搜索树的特性, 左>根>右
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null) {
return null;
}
if (root.val > Math.max(p.val, q.val)) {
return lowestCommonAncestor(root.left, p, q);
} else if (root.val < Math.min(p.val, q.val)) {
return lowestCommonAncestor(root.right, p, q);
} else {
return root;
}
}
二叉树的公共父节点
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/
没有搜索树的特性了
这个说过了:https://www.jianshu.com/p/f79092ce15b3
public TreeNode lowestCommonAncestor2(TreeNode root, TreeNode p, TreeNode q) {
if (root == null || p == root || q == root) {
return root;
}
TreeNode left = lowestCommonAncestor2(root.left, p, q);
TreeNode right = lowestCommonAncestor2(root.right, p, q);
if (left != null && right != null) {
return root;
}
return left != null ? left : right;
}
网友评论