zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    《架构师》反思:系统可靠性
    表现力(转)
    4月反思
    30天敏捷结果(10) 强化你的一周
    认真对待学习(2月反思)
    Sort By Double
    12月反思 组内设计评审会议
    WPF框架的内存泄漏BUG
    OpenExpressApp 框架结构(2)
    绑定子类的泛型基类,反模式?
  • 原文地址:https://www.cnblogs.com/caiyanhu/p/7054338.html
Copyright © 2011-2022 走看看