标签:code cti i+1 广度 nod ret 函数定义 树节点 节点
二叉树节点函数定义:
/** * Definition for a binary tree node. */ function TreeNode(val){ this.val = val; this.left = this.right = null; }
层次遍历构建二叉树(广度优先)
function createBinaryTree(arr){ var p = new TreeNode(arr[0]); var k = 0; var len = arr.length; var buildTree = function(node, i){ if(2*i+1<len){ node.left = new TreeNode(arr[2*i+1]); node.left && buildTree(node.left, 2*i+1) } if(2*i+2<len){ node.right = new TreeNode(arr[2*i+2]); node.right && buildTree(node.right, 2*i+2); } }; buildTree(p, 0); return p; }
给定一个数组(按层次遍历的规律排序)测试:
var arr = [3,9,20,null,null,15,7]; var tree = createBinaryTree(arr); console.log(tree);
标签:code cti i+1 广度 nod ret 函数定义 树节点 节点
原文地址:https://www.cnblogs.com/davidxu/p/13539171.html