Skip to content

Commit d725455

Browse files
committed
add lca
1 parent cc228fc commit d725455

File tree

3 files changed

+64
-0
lines changed

3 files changed

+64
-0
lines changed

lowest-common-ancestor-of-a-binary-tree/README.md

Whitespace-only changes.
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
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+
}
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
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 %}

0 commit comments

Comments
 (0)