1+ const qian = [ 'a' , 'c' , 'f' , 'g' , 'b' , 'd' , 'e' ] ;
2+ const zhong = [ 'f' , 'c' , 'g' , 'a' , 'd' , 'b' , 'e' ] ;
3+
4+ function Node ( value ) {
5+ this . value = value ;
6+ this . left = null ;
7+ this . right = null ;
8+ }
9+ function f1 ( qian , zhong ) {
10+ if ( qian == null || zhong == null ||
11+ qian . length == 0 || zhong . length == 0
12+ || qian . length != zhong . length )
13+ return null ;
14+ const root = new Node ( qian [ 0 ] ) ;
15+ let index = zhong . indexOf ( root . value ) ;
16+ let leftQian = qian . slice ( 1 , index + 1 ) ;
17+ let rightQian = qian . slice ( index + 1 , qian . length ) ;
18+ let leftZhong = zhong . slice ( 0 , index ) ;
19+ let rightZhong = zhong . slice ( index + 1 , zhong . length ) ;
20+ root . left = f1 ( leftQian , leftZhong ) ;
21+ root . right = f1 ( rightQian , rightZhong ) ;
22+ return root ;
23+ }
24+ const root = f1 ( qian , zhong ) ;
25+ console . log ( root ) ;
26+ /**
27+ * 深度优先搜索
28+ * @param root
29+ * @param target
30+ */
31+ function seachHeight ( root , target ) {
32+ if ( root == null ) return false ;
33+ if ( root . value == target ) return true ;
34+ const left = seachHeight ( root . left ) ;
35+ const right = seachHeight ( root . right ) ;
36+ return left || right ;
37+ }
38+ // console.log(seachHeight((root,'f')))
39+ /**
40+ * 广度优先搜索 将二叉树的每一层分别查找
41+ * @param rootList
42+ * @param taget
43+ */
44+ function seachWidth ( root , target ) {
45+ if ( root == null ) return false ;
46+ let left , right ;
47+ if ( root != null && root . value == target ) {
48+ return true ;
49+ } else {
50+ left = seachWidth ( root . left , target ) ;
51+ right = seachWidth ( root . right , target ) ;
52+ }
53+ return left || right ;
54+ }
55+
56+
57+ console . log ( seachWidth ( root , 'e' ) ) ;
0 commit comments