Skip to content

Commit

Permalink
feat: azl397985856#236 add python 🐍 solution (azl397985856#278)
Browse files Browse the repository at this point in the history
  • Loading branch information
jojoxiaojing authored and azl397985856 committed Jan 16, 2020
1 parent 34f3f06 commit c647379
Showing 1 changed file with 29 additions and 52 deletions.
81 changes: 29 additions & 52 deletions problems/236.lowest-common-ancestor-of-a-binary-tree.md
Original file line number Diff line number Diff line change
Expand Up @@ -70,60 +70,11 @@ p and q are different and both values will exist in the binary tree.

## 代码

```js
代码支持: JavaScript, Python3

- JavaScript Code:

/*
* @lc app=leetcode id=236 lang=javascript
*
* [236] Lowest Common Ancestor of a Binary Tree
*
* https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/description/
*
* algorithms
* Medium (35.63%)
* Total Accepted: 267.3K
* Total Submissions: 729.2K
* Testcase Example: '[3,5,1,6,2,0,8,null,null,7,4]\n5\n1'
*
* 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.
*
*
*/
```js
/**
* Definition for a binary tree node.
* function TreeNode(val) {
Expand All @@ -147,6 +98,32 @@ var lowestCommonAncestor = function(root, p, q) {
};
```

- Python Code:

``` python
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None

class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if not root or root == p or root == q:
return root
left = self.lowestCommonAncestor(root.left, p, q)
right = self.lowestCommonAncestor(root.right, p, q)

if not left:
return right
if not right:
return left
else:
return root

```

## 扩展
如果递归的结束条件改为`if (!root || root.left === p || root.right === q) return root;` 代表的是什么意思,对结果有什么样的影响?

0 comments on commit c647379

Please sign in to comment.