Given the root and two nodes in a Binary Tree. Find the lowest common ancestor(LCA) of the two nodes.
The lowest common ancestor is the node with largest depth which is the ancestor of both nodes.
Return null
if LCA does not exist.
Example1
Input:
{4, 3, 7, #, #, 5, 6}
3 5
5 6
6 7
5 8
Output:
4
7
7
null
Explanation:
4
/ \
3 7
/ \
5 6
LCA(3, 5) = 4
LCA(5, 6) = 7
LCA(6, 7) = 7
LCA(5, 8) = null
Example2
Input:
{1}
1 1
Output:
1
Explanation:
The tree is just a node, whose value is 1.
node A or node B may not exist in tree.
Each node has a different value
AC代码:
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
this.val = val
this.left, this.right = None, None
"""
class Solution:
"""
@param: root: The root of the binary tree.
@param: A: A TreeNode
@param: B: A TreeNode
@return: Return the LCA of the two nodes.
"""
def lowestCommonAncestor3(self, root, A, B):
if(root is None):
return None
#write your code here
path = [root]
f1, pathA = self.dfs(root, path, A)
path = [root]
f2, pathB = self.dfs(root, path, B)
print(f1)
print(f2)
if((f1 and f2) == 0):#注意这里符号运行的先后顺序!!!
return None
for i in range(min(len(pathA),len(pathB)) - 1, -1, -1):
if(pathA[i] == pathB[i]):
return pathA[i]
return None
#return path[0]
def dfs(self, root, path, target):
if(root == target):
#print(root.val)
return 1, path
if(root.left):
path.append(root.left)
#print("#")
flag, path = self.dfs(root.left, path, target)
if(flag == 1):
return 1, path
path.pop()
if(root.right):
path.append(root.right)
#print("$")
flag, path = self.dfs(root.right, path, target)
if(flag == 1):
return 1, path
path.pop()
return 0, path
对于用dfs找特定点的路径还是不是很熟练。不过这次基本上都是自己码出来的代码。思路是分别找到两个点的路径,如a = [4,7,6]和 b = [4,7,5,2],然后从最高的那个点的长度开始比较路径,找到第一个相同点,如这里在树里比较高的点是a,那么就取a[2]和b[2]开始比较,不等(6和5),则 i -= 1,取a[1]和b[1],发现相等,则最近公共祖先为7这个点。
注意点有一个, 主要是Python的语法问题。在代码段中给予注释了。若 f1 == 0, f2 == 0,那么 (f1 and f2) == 0 是True, 但是若写成 f1 and f2 == 0 则为 0,因为先计算了后面的值(0 and 1)。