JS二叉树的操作
二叉树的构造
1 // 二叉树的数据结构 2 function treeNode(val) { 3 this.val = val; 4 this.left = null; 5 this.right = null; 6 } 7 var nodeRoot = new treeNode("root"); 8 var nodeA = new treeNode('A'); 9 var nodeB = new treeNode('B'); 10 var nodeC = new treeNode('C'); 11 var nodeD = new treeNode('D'); 12 var nodeE = new treeNode('E'); 13 var nodeF = new treeNode('F'); 14 nodeA.left = nodeC; 15 nodeA.right = nodeD; 16 nodeB.left = nodeE; 17 nodeB.right = nodeF; 18 nodeRoot.left = nodeA; 19 nodeRoot.right = nodeB;
二叉树的遍历
深度优先:
1 function dFirstTravel(root) { 2 if (root === null) { 3 return; 4 } 5 console.log(root.val); 6 dFirstTravel(root.left); 7 dFirstTravel(root.right); 8 }
广度优先:
1 function wFirstTravel(nodeRoot) { 2 // 1初始化一个队列,并把根结点入列队; 3 4 // 2当队列为非空时,循环执行步骤3到步骤5,否则执行6; 5 6 // 3出队列取得一个结点,访问该结点; 7 8 // 4若该结点的左子树为非空,则将该结点的左子树入队列; 9 10 // 5若该结点的右子树为非空,则将该结点的右子树入队列; 11 12 // 6结束。 13 var queue = []; 14 queue.push(nodeRoot); 15 while (queue.length > 0) { 16 var node = queue.shift(); 17 console.log(node.val); 18 if (node.left !== null) { 19 queue.push(node.left); 20 } 21 if (node.right !== null) { 22 queue.push(node.right); 23 } 24 } 25 }
翻转二叉树
1 function invertTree(root) { 2 if (root === null) { 3 return root; 4 } 5 var tmp = root.left; 6 root.left = root.right; 7 root.right = tmp; 8 if (root.left !== null) { 9 arguments.callee(root.left); 10 } 11 if (root.right !== null) { 12 arguments.callee(root.right); 13 } 14 return root; 15 }