Skip to content

Commit 8b05091

Browse files
author
橙澈
committed
week03
1 parent ebd5e4f commit 8b05091

2 files changed

Lines changed: 25 additions & 0 deletions

File tree

Week03/code.js

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
// 从前序与中序遍历序列构造二叉树
2+
var buildTree = function(preorder, inorder) {
3+
if(!preorder.length) return null
4+
const node = new TreeNode(preorder[0])
5+
const index = inorder.indexOf(preorder[0])
6+
const inLeft = inorder.slice(0, index)
7+
const inRight = inorder.slice(index + 1)
8+
const preLeft = preorder.slice(1, index + 1)
9+
const preRight = preorder.slice(index + 1)
10+
node.left = buildTree(preLeft, inLeft)
11+
node.right = buildTree(preRight, inRight)
12+
return node
13+
};
14+
15+
16+
// 二叉树的最近公共祖先
17+
var lowestCommonAncestor = function(root, p, q) {
18+
if (root === null) return null
19+
if (root == p || root == q) return root;
20+
let left = lowestCommonAncestor(root.left, p , q)
21+
let right = lowestCommonAncestor(root.right, p , q)
22+
if (!left) return right;
23+
if (!right) return left;
24+
return root;
25+
};

Week03/新建笔记.png

336 KB
Loading

0 commit comments

Comments
 (0)