File tree Expand file tree Collapse file tree 3 files changed +64
-0
lines changed
lowest-common-ancestor-of-a-binary-tree Expand file tree Collapse file tree 3 files changed +64
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * Definition for a binary tree node.
3
+ * public class TreeNode {
4
+ * int val;
5
+ * TreeNode left;
6
+ * TreeNode right;
7
+ * TreeNode(int x) { val = x; }
8
+ * }
9
+ */
10
+ public class Solution {
11
+
12
+ TreeNode lca ;
13
+
14
+ TreeNode other ;
15
+
16
+ boolean containOther (TreeNode root ){
17
+
18
+ if (root == null ) return false ;
19
+
20
+ if (root == other ) return true ;
21
+
22
+ return containOther (root .left ) || containOther (root .right );
23
+ }
24
+
25
+ void inorder (TreeNode root , TreeNode p , TreeNode q ){
26
+ if (lca != null ) return ;
27
+
28
+ if (root == null ) return ;
29
+
30
+ if (other == null ) inorder (root .left , p , q );
31
+
32
+ if (other == null ){
33
+ if (root == p ){
34
+ other = q ;
35
+ } else if (root == q ){
36
+ other = p ;
37
+ }
38
+ }
39
+
40
+ if (other != null ){
41
+ // left contain one, need other
42
+ if (root == other || containOther (root .right )){
43
+ lca = root ;
44
+ }
45
+ }
46
+
47
+ if (other == null ) inorder (root .right , p , q );
48
+ }
49
+
50
+
51
+ public TreeNode lowestCommonAncestor (TreeNode root , TreeNode p , TreeNode q ) {
52
+ // a bit ugly
53
+ inorder (root , p , q );
54
+
55
+ return lca ;
56
+ }
57
+ }
Original file line number Diff line number Diff line change
1
+ ---
2
+ layout : solution
3
+ title : Lowest Common Ancestor of a Binary Tree
4
+ date : 2015-07-26 16:03:27+08:00
5
+ leetcode_id : 236
6
+ ---
7
+ {% include_relative README.md %}
You can’t perform that action at this time.
0 commit comments