zoukankan      html  css  js  c++  java
  • 4.二叉树的前序-中序-后序遍历(JavaScript版)

    使用JavaScript实现二叉树的前序遍历,中序遍历,后序遍历

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
    </head>
    <body>
        <script>
            function Node(value){
                this.value = value;
                this.left = null;
                this.right = null;
            }
    
            var nodeA = new Node("a");
            var nodeB = new Node("b");
            var nodeC = new Node("c");
            var nodeD = new Node("d");
            var nodeE = new Node("e");
            var nodeF = new Node("f");
            var nodeG = new Node("g");
    
            nodeA.left = nodeB;
            nodeA.right = nodeC;
            nodeB.left = nodeD;
            nodeB.right = nodeE;
            nodeC.left = nodeF;
            nodeC.right = nodeG;
    
    //前序遍历:先打印当前节点,再打印左边子树的节点,再打印右边子树的节点
    //中序遍历:先打印左边子树的节点,再打印当前节点,再打印右边子树的节点
    //后序遍历:先打印左边子树的节点,再打印右边子树的节点,再打印当前节点
    
    
            //-------前序遍历---begin-----//
            function DLR(root){//前序遍历
                if(root == null) return;
                console.log(root.value);//先输出
                DLR(root.left);
                DLR(root.right);
            }
            DLR(nodeA);//a b d e c f g
            //-------前序遍历---end-----//
    
            //-------中序遍历---begin-----//
            function LDR(root){//前序遍历
                if(root == null) return;
                LDR(root.left);
                console.log(root.value);
                LDR(root.right);
            }
            LDR(nodeA);//d b e a f c g
            //-------中序遍历---end-----//
    
            //-------后序遍历---begin-----//
            function LRD(root){//前序遍历
                if(root == null) return;
                LRD(root.left);
                LRD(root.right);
                console.log(root.value);
            }
            LRD(nodeA);//d e b f g c a
            //-------后序遍历---end-----//
        </script>
    </body>
    </html>
    二叉树遍历
  • 相关阅读:
    盘点 | 2020年金融科技大事记:监管与后疫情
    2020年业务安全领域12大事件
    安装zsh时git太慢,换代理
    springboot 日志处理 aop
    DataPipeline荣获湾区创见&#183;2020网络安全大会 TECHSPARK 十强奖
    PI-S4 Proxy相关配置
    PI-海外银企直联方案
    Mendix-Websites
    crawler-美国GDP数据预测
    AST-web端javascript逆向杀器之认识AST
  • 原文地址:https://www.cnblogs.com/lanshanxiao/p/13183122.html
Copyright © 2011-2022 走看看