@@ -70,7 +70,11 @@ class Solution:
70
70
return root
71
71
left = self .lowestCommonAncestor(root.left, p, q)
72
72
right = self .lowestCommonAncestor(root.right, p, q)
73
- return right if left is None else (left if right is None else root)
73
+ if left is None :
74
+ return right
75
+ if right is None :
76
+ return left
77
+ return root
74
78
```
75
79
76
80
### ** Java**
@@ -89,12 +93,12 @@ class Solution:
89
93
*/
90
94
class Solution {
91
95
public TreeNode lowestCommonAncestor (TreeNode root , TreeNode p , TreeNode q ) {
92
- if (root == null || root == p || root == q) {
93
- return root;
94
- }
96
+ if (root == null || root == p || root == q) return root;
95
97
TreeNode left = lowestCommonAncestor(root. left, p, q);
96
98
TreeNode right = lowestCommonAncestor(root. right, p, q);
97
- return left == null ? right : (right == null ? left : root);
99
+ if (left == null ) return right;
100
+ if (right == null ) return left;
101
+ return root;
98
102
}
99
103
}
100
104
```
@@ -116,14 +120,12 @@ class Solution {
116
120
* @return {TreeNode}
117
121
*/
118
122
var lowestCommonAncestor = function (root , p , q ) {
119
- if (! root) return null ;
120
- if (root === p || root === q) return root;
121
- let left = lowestCommonAncestor (root .left , p, q);
122
- let right = lowestCommonAncestor (root .right , p, q);
123
- if (left && right) return root;
124
- if (left) return left;
125
- if (right) return right;
126
- return null ;
123
+ if (! root || root == p || root == q) return root;
124
+ const left = lowestCommonAncestor (root .left , p, q);
125
+ const right = lowestCommonAncestor (root .right , p, q);
126
+ if (! left) return right;
127
+ if (! right) return left;
128
+ return root;
127
129
};
128
130
```
129
131
0 commit comments