Skip to content

Commit

Permalink
ac Lowest Common Ancestor of a Binary Tree
Browse files Browse the repository at this point in the history
  • Loading branch information
fa-ge committed Nov 5, 2016
1 parent 65ef0c7 commit baa2054
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 0 deletions.
22 changes: 22 additions & 0 deletions 236-Lowest-Common-Ancestor-of-a-Binary-Tree/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
### 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](https://en.wikipedia.org/wiki/Lowest_common_ancestor): “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”

_______3______
/ \
___5__ ___1__
/ \ / \
6 _2 0 8
/ \
7 4

For example, the lowest common ancestor (LCA) of nodes `5` and `1` is `3`. Another example is LCA of nodes `5` and `4` is `5`, since a node can be a descendant of itself according to the LCA definition.

### 方法(一)
二种情况。
1. v和w有直系关系,就像5和6或者6和3
2. v和w没有直系关系
第二种情况一定分别在T节点的左右子树上,而且也仅有T节点的左右子树分别有这两个节点。这里用递归找左右子树中是否有这两个节点。如果左右子树中都有,那祖先节点就是当前节点,如果只有左或者只有右子树上找到节点,说明是第一种情况返回找到的节点就可以了。

43 changes: 43 additions & 0 deletions 236-Lowest-Common-Ancestor-of-a-Binary-Tree/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @param {TreeNode} p
* @param {TreeNode} q
* @return {TreeNode}
*/
var lowestCommonAncestor = function(root, p, q) {
if (root == p || root == q || !root) {
return root
}
let left = lowestCommonAncestor(root.left, p, q)
let right = lowestCommonAncestor(root.right, p, q)

if (left && right) {
return root
} else if (left) {
return left
} else if (right) {
return right
} else {
return null
}
};
function TreeNode(val) {
this.val = val;
this.left = this.right = null;
}
const root = new TreeNode(4)
root.left = new TreeNode(2)
root.right = new TreeNode(6)
root.left.left = new TreeNode(1)
root.left.right = new TreeNode(3)
root.right.left = new TreeNode(5)
root.right.right = new TreeNode(7)

console.log(lowestCommonAncestor(root, root.right.left, root.right))

0 comments on commit baa2054

Please sign in to comment.