update tree

This commit is contained in:
ranwenjie
2021-11-15 01:29:08 +08:00
parent 4a31531cf6
commit ec09f22df4
2 changed files with 35 additions and 16 deletions
+4 -5
View File
@@ -232,7 +232,6 @@ public static LinkedNode mergeSeqLink(LinkedNode l1, LinkedNode l2){
```Java
TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
// base case
if (root == null) return null;
@@ -240,17 +239,17 @@ TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
TreeNode left = lowestCommonAncestor(root.left, p, q);
TreeNode right = lowestCommonAncestor(root.right, p, q);
// 情况 1
// 情况 1 :p, q 在 root 为根的树中
if (left != null && right != null) {
return root;
}
// 情况 2
// 情况 2 :p, q 不在 在 root 为根的树中
if (left == null && right == null) {
return null;
}
// 情况 3
// 情况 3 : p, q 只有1个在root 为根的树中
return left == null ? right : left;
}
}
```
+20
View File
@@ -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;
}
```