xiankun.zhu
BAN USER1. find path of both node from root
2. compare the path,until find different ith, return path[i-1]
time complexity is O(n+n+logn)=O(n)
TreeNode lca(TreeNode root, TreeNode a, TreeNode b){
List<TreeNode> pathA = new ArrayList<>();
List<TreeNode> pathB = new ArrayList<>();
dfs(root, a, pathA);
dfs(root, b, pathB);
int i = 0;
while(pathA.get(i) == pathB.get(i)) i++;
return pathA.get(i-1);
}
boolean dfs(TreeNode root, Node a, List<TreeNode> path){
if(root==null) return false;
path.add(root);
if(root.equals(a)) return true;
if(dfs(root.left, a, path)) return true;
if(dfs(root.rigth, a, path)) return true;
path.remove(path.length() - 1);
return false;
}
my easy to understand answer:
1. find path of both node from root
2. compare the path,until find different ith, return path[i-1]
time complexity is O(n+n+logn)=O(n)
TreeNode lca(TreeNode root, TreeNode a, TreeNode b){
List<TreeNode> pathA = new ArrayList<>();
List<TreeNode> pathB = new ArrayList<>();
dfs(root, a, pathA);
dfs(root, b, pathB);
int i = 0;
while(pathA.get(i) == pathB.get(i)) i++;
return pathA.get(i-1);
}
boolean dfs(TreeNode root, Node a, List<TreeNode> path){
if(root==null) return false;
path.add(root);
if(root.equals(a)) return true;
if(dfs(root.left, a, path)) return true;
if(dfs(root.rigth, a, path)) return true;
path.remove(path.length() - 1);
return false;
}
RepAsaDills, HR Executive Trainee at Cerner Corporation
I 'm Asa Dills, My role of the Public Housing Manager (PHM) is complex. the financial viability of the property ...
RepSpent 2001-2006 licensing the elderly in Jacksonville, FL. Spent 2001-2004 consulting about Break Up Spell. Spent two years deploying crickets ...
Repqueznister, Android test engineer at Aspire Systems
I supervise the day-to-day operations of the store. assign duties. Determine staffing requirements, oversee their hiring, and, when needed, dismiss ...
Repliliylinda619, Area Sales Manager at Alliance Global Servies
My name is Sarah Torres and I am a Fitness director in the Independent Planners. I am a very kind ...
the method can't be named DFS, it can be named as backtracking.
- xiankun.zhu May 09, 2016