二叉树遍历

二叉树遍历

结构如下图
A
C
F
G
B
D
E
前序遍历

顺序:先输出自己,在输出左边,然后输出右边

	 function Node(value){
            this.value = value;
            this.left = null;
            this.right = null;
        }
        var a = new Node("A");
        var b = new Node("B");
        var c = new Node("C");
        var d = new Node("D");
        var e = new Node("E");
        var f = new Node("F");
        var g = new Node("G");

        a.left = c;
        a.right = b;

        c.left = f;
        c.right = g;

        b.left = d;
        b.right = e;

        function fun(root){
            if(root == null){
                return
            };
            console.log(root.value);   //先输出自己
            fun(root.left)   // 输出左边
            fun(root.right)   // 输出右边
        }   
        fun(a)
        //最终输出结果 A、C、F、G、B、D、E
中序遍历

顺序:先输出左边,在输出自己,然后输出右边

	  function Node(value){
            this.value = value;
            this.left = null;
            this.right = null;
        }
       	var a = new Node("A");
        var b = new Node("B");
        var c = new Node("C");
        var d = new Node("D");
        var e = new Node("E");
        var f = new Node("F");
        var g = new Node("G");


        a.left = c;
        a.right = b;

        c.left = f;
        c.right = g;

        b.left = d;
        b.right = e;

        function fun(root){
            if(root == null){
                return
            };
            fun(root.left)   // 输出左边
            console.log(root.value);   //输出自己
            fun(root.right)   // 输出右边
        }   
        fun(a)
        //输出 F、C、G、A、D、B、E
后续遍历

顺序:先输出左边,在输出右边,然后输出自己

	function Node(value){
            this.value = value;
            this.left = null;
            this.right = null;
        }
        var a = new Node("A");
        var b = new Node("B");
        var c = new Node("C");
        var d = new Node("D");
        var e = new Node("E");
        var f = new Node("F");
        var g = new Node("G");


        a.left = c;
        a.right = b;

        c.left = f;
        c.right = g;

        b.left = d;
        b.right = e;

        function fun(root){
            if(root == null){
                return
            };
            fun(root.left)   // 输出左边
            fun(root.right)   // 输出右边
            console.log(root.value);   //输出自己
        }   
        fun(a)
        //输出:F、G、C、D、E、B、A
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值