## 6-236. Lowest Common Ancestor of a Binary Tree

Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.

According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”

Given the following binary tree:  root = [3,5,1,6,2,0,8,null,null,7,4]

Example 1:

```Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
Output: 3
Explanation: The LCA of nodes `5` and `1` is `3.`
```

Example 2:

```Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
Output: 5
Explanation: The LCA of nodes `5` and `4` is `5`, since a node can be a descendant of itself according to the LCA definition.
```

Note:

• All of the nodes' values will be unique.
• p and q are different and both values will exist in the binary tree.

``` 1 # Definition for a binary tree node.
2 # class TreeNode(object):
3 #     def __init__(self, x):
4 #         self.val = x
5 #         self.left = None
6 #         self.right = None
7
8 class Solution(object):
9     def lowestCommonAncestor(self, root, p, q):
10         """
11         :type root: TreeNode
12         :type p: TreeNode
13         :type q: TreeNode
14         :rtype: TreeNode
15         """
16         # Stack for tree traversal
17         stack = [root]
18         # Dictionary for parent pointers
19         parent = {root: None}
20         # Iterate until we find both the nodes p and q
21         while p not in parent or q not in parent:
22
23             node = stack.pop()
24
25             # While traversing the tree, keep saving the parent pointers.
26             if node.left:
27                 parent[node.left] = node
28                 stack.append(node.left)
29             if node.right:
30                 parent[node.right] = node
31                 stack.append(node.right)
32
33         # Ancestors set() for node p.
34         ancestors = set()
35
36         # Process all ancestors for node p using parent pointers.
37         while p:
39             p = parent[p]
40
41         # The first ancestor of q which appears in
42         # p's ancestor set() is their lowest common ancestor.
43         while q not in ancestors:
44             q = parent[q]
45         return q```

Python的pop()函数用于移除列表中的一个元素（默认最后一个元素），并返回该元素的值。

stack在代码中是一个动态数组，最初stack=[TreeNode(3)]（以下直接以数字表示对应位置的树节点）。parent最初只是一个空的树节点。

parent树为：

3

/     \

5        1

parent树为：

3

/         \

5                 1

/     \

0        8

parent树为：

3

/         \

5                 1

/     \

0        8

parent树为：

3

/         \

5                 1

/     \

0        8

parent树为：

3

/         \

5                 1

/    \             /     \

6       2         0        8

0条评论