update tree
This commit is contained in:
+15
-16
@@ -232,25 +232,24 @@ public static LinkedNode mergeSeqLink(LinkedNode l1, LinkedNode l2){
|
||||
|
||||
|
||||
```Java
|
||||
|
||||
TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
|
||||
// base case
|
||||
if (root == null) return null;
|
||||
if (root == p || root == q) return root;
|
||||
// base case
|
||||
if (root == null) return null;
|
||||
if (root == p || root == q) return root;
|
||||
|
||||
TreeNode left = lowestCommonAncestor(root.left, p, q);
|
||||
TreeNode right = lowestCommonAncestor(root.right, p, q);
|
||||
// 情况 1
|
||||
if (left != null && right != null) {
|
||||
return root;
|
||||
TreeNode left = lowestCommonAncestor(root.left, p, q);
|
||||
TreeNode right = lowestCommonAncestor(root.right, p, q);
|
||||
// 情况 1 :p, q 在 root 为根的树中
|
||||
if (left != null && right != null) {
|
||||
return root;
|
||||
}
|
||||
// 情况 2 :p, q 不在 在 root 为根的树中
|
||||
if (left == null && right == null) {
|
||||
return null;
|
||||
}
|
||||
// 情况 3 : p, q 只有1个在root 为根的树中
|
||||
return left == null ? right : left;
|
||||
}
|
||||
// 情况 2
|
||||
if (left == null && right == null) {
|
||||
return null;
|
||||
}
|
||||
// 情况 3
|
||||
return left == null ? right : left;
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
|
||||
@@ -117,6 +117,26 @@ TreeNode invertTree(TreeNode root) {
|
||||
分析:求数中两个结点的最低共同结点是面试中经常出现的一个问题。这个问题至少有两个变种。
|
||||
|
||||
|
||||
```
|
||||
TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
|
||||
// base case
|
||||
if (root == null) return null;
|
||||
if (root == p || root == q) return root;
|
||||
|
||||
TreeNode left = lowestCommonAncestor(root.left, p, q);
|
||||
TreeNode right = lowestCommonAncestor(root.right, p, q);
|
||||
// 情况 1 :p, q 在 root 为根的树中
|
||||
if (left != null && right != null) {
|
||||
return root;
|
||||
}
|
||||
// 情况 2 :p, q 不在 在 root 为根的树中
|
||||
if (left == null && right == null) {
|
||||
return null;
|
||||
}
|
||||
// 情况 3 : p, q 只有1个在root 为根的树中
|
||||
return left == null ? right : left;
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user