File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 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+ } ;
You can’t perform that action at this time.
0 commit comments