題目:給定一個二叉搜索樹, 找到該樹中兩個指定節(jié)點的最近公共祖先扭弧。
練習地址
https://leetcode-cn.com/problems/er-cha-sou-suo-shu-de-zui-jin-gong-gong-zu-xian-lcof/
參考答案
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
TreeNode common = root;
while (common != null) {
if (common.val > p.val && common.val > q.val) {
common = common.left;
} else if (common.val < p.val && common.val < q.val) {
common = common.right;
} else {
return common;
}
}
return common;
}
}
復雜度分析
- 時間復雜度:O(n)常空。
- 空間復雜度:O(1)。
題目:給定一個二叉樹, 找到該樹中兩個指定節(jié)點的最近公共祖先赠摇。
練習地址
https://leetcode-cn.com/problems/er-cha-shu-de-zui-jin-gong-gong-zu-xian-lcof/
參考答案
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null || p == null || q == null) {
return null;
}
LinkedList<TreeNode> path1 = new LinkedList<>();
getNodePath(root, p, path1);
LinkedList<TreeNode> path2 = new LinkedList<>();
getNodePath(root, q, path2);
return getLastCommonNode(path1, path2);
}
private boolean getNodePath(TreeNode root, TreeNode node, LinkedList<TreeNode> path) {
if (root == null) {
return false;
}
path.add(root);
if (root == node) {
return true;
}
boolean found = getNodePath(root.left, node, path);
if (!found) {
found = getNodePath(root.right, node, path);
}
if (!found) {
path.removeLast();
}
return found;
}
private TreeNode getLastCommonNode(LinkedList<TreeNode> path1, LinkedList<TreeNode> path2) {
Iterator<TreeNode> iterator1 = path1.iterator();
Iterator<TreeNode> iterator2 = path2.iterator();
TreeNode last = null;
while (iterator1.hasNext() && iterator2.hasNext()) {
TreeNode node = iterator1.next();
if (node == iterator2.next()) {
last = node;
} else {
break;
}
}
return last;
}
}
復雜度分析
- 時間復雜度:O(n)。
- 空間復雜度:O(logn)莲蜘。