|
| 1 | +""" |
| 2 | +Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. |
| 3 | +
|
| 4 | +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).” |
| 5 | +
|
| 6 | +Given the following binary tree: root = [3,5,1,6,2,0,8,null,null,7,4] |
| 7 | +
|
| 8 | + _______3______ |
| 9 | + / \ |
| 10 | + ___5__ ___1__ |
| 11 | + / \ / \ |
| 12 | + 6 _2 0 8 |
| 13 | + / \ |
| 14 | + 7 4 |
| 15 | +Example 1: |
| 16 | +
|
| 17 | +Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1 |
| 18 | +Output: 3 |
| 19 | +Explanation: The LCA of of nodes 5 and 1 is 3. |
| 20 | +Example 2: |
| 21 | +
|
| 22 | +Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4 |
| 23 | +Output: 5 |
| 24 | +Explanation: The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself |
| 25 | + according to the LCA definition. |
| 26 | +Note: |
| 27 | +
|
| 28 | +All of the nodes' values will be unique. |
| 29 | +p and q are different and both values will exist in the binary tree. |
| 30 | +
|
| 31 | +
|
| 32 | +给一颗二叉树,找出某两个子节点的最小公共祖先。 |
| 33 | +思路: |
| 34 | +
|
| 35 | +用递归: |
| 36 | + 1. 用递归找到符合条件的子节点。 找到后的子节点会返回为一个具体的 TreeNode,找不到的话则是 None。 |
| 37 | + 2. 之后判断 是不是两个都找到了,最先知道两个都找到的点即为最小公共祖先。 |
| 38 | + 3. q为p子节点,或p为q子节点的情况: |
| 39 | + 由于是唯一的,所以出现这种情况一定有一边返回是None,所以返回不是None的一边即可。 |
| 40 | +
|
| 41 | +普通的二叉树要递归的话是这样: |
| 42 | +
|
| 43 | +# do something |
| 44 | +
|
| 45 | +if root.right: |
| 46 | + right = recursive(root.right) |
| 47 | +if root.left: |
| 48 | + left = recursive(root.left) |
| 49 | +
|
| 50 | +# do something |
| 51 | +
|
| 52 | +按照上面的思路加工一下即可。 |
| 53 | +
|
| 54 | +测试地址: |
| 55 | +https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/description/ |
| 56 | +
|
| 57 | +""" |
| 58 | +# Definition for a binary tree node. |
| 59 | +# class TreeNode(object): |
| 60 | +# def __init__(self, x): |
| 61 | +# self.val = x |
| 62 | +# self.left = None |
| 63 | +# self.right = None |
| 64 | + |
| 65 | +class Solution(object): |
| 66 | + def lowestCommonAncestor(self, root, p, q): |
| 67 | + """ |
| 68 | + :type root: TreeNode |
| 69 | + :type p: TreeNode |
| 70 | + :type q: TreeNode |
| 71 | + :rtype: TreeNode |
| 72 | + """ |
| 73 | + if root.val == p.val or root.val == q.val: |
| 74 | + return root |
| 75 | + |
| 76 | + right = None |
| 77 | + left = None |
| 78 | + |
| 79 | + if root.right: |
| 80 | + right = self.lowestCommonAncestor(root.right, p, q) |
| 81 | + if root.left: |
| 82 | + left = self.lowestCommonAncestor(root.left, p, q) |
| 83 | + |
| 84 | + if right and left: |
| 85 | + return root |
| 86 | + |
| 87 | + if right: |
| 88 | + return right |
| 89 | + |
| 90 | + if left: |
| 91 | + return left |
0 commit comments