利用层次遍历原理构建二叉树

层次遍历构建二叉树:

1.定义二叉树节点:

1 function TreeNode(val){
2     this.val = val;
3     this.left = this.right = null;
4 }

2.层次遍历构建二叉树:

 1 function createTree(arr){
 2     if(!arr||!arr.length)return null;
 3     var root = new TreeNode(arr.shift());
 4     var list = [root];
 5     while(arr.length){
 6         var tmpList = [];
 7         for(var i=0;i<list.length;i++){
 8             var p = list[i];
 9             p.left = new TreeNode(arr.shift());
10             p.right = new TreeNode(arr.shift());
11             if(p.left){
12                tmpList.push(p.left);
13             }
14             if(p.right){
15                tmpList.push(p.right);
16             }
17         }
18         list = tmpList;
19     }
20     return root;
21 }

3.测试

//var arr = [1,2,2,3,4,4,3];
var arr = [1,2,2,null,3,null,3];
var root = createTree(arr);
console.log(root);

猜你喜欢

转载自www.cnblogs.com/davidxu/p/9031055.html