二叉树后序遍历JavaScript递归和非递归实现方法

//后序遍历,左孩子-右孩子-根结点
var TreeNode = {
    val: 1,
    left: {
        val: 2,
        left: {
          val: 4,
        },
        right: {
            val: 5
        }
    },
    right: {
        val: 3,
        left: {
            val: 6,
        },
        right: {
            val: 7
        }
    }
};

var postOrderRecur = function(root){
    var list = [];
    var postOrder = function(root){
        if(root === undefined){
            return root;
        }

        postOrder(root.left);
        postOrder(root.right);
        list.push(root.val);
    }
    postOrder(root);
    return list;
}

// 使用两个栈结构
var postOrderUnRecur = function(root){
    var list = [];
    if(root !== undefined){
        var s1 = [];
        var s2 = [];
        s1.push(root);
        while(s1.length !== 0){
            head = s1.pop();
            s2.push(head);
            if(head.left !== undefined){
                s1.push(head.left);
            }
            if(head.right !== undefined){
                s1.push(head.right);
            }
        }
        while(s2.length !== 0){
            var item = s2.pop();
            list.push(item.val);
        }
    }
    return list;
}

// var listRecur = postOrderRecur(TreeNode);
// console.log('递归后序遍历', listRecur);

var listUnRecur = postOrderUnRecur(TreeNode);
console.log('非递归后序遍历', listUnRecur);

// [4, 5, 2, 6, 7, 3, 1]

你可能感兴趣的:(二叉树后序遍历JavaScript递归和非递归实现方法)