JavaScript之迭代算法实现二叉树深度优先遍历

创建二叉树结构

function TreeNode(val) {
	this.val = val;
	this.left = this.right = null;
}
let root = new TreeNode(1)
let node2 = new TreeNode(2)
let node3 = new TreeNode(3)
let node4 = new TreeNode(4)
let node5 = new TreeNode(5)
let node6 = new TreeNode(6)
let node7 = new TreeNode(7)
root.left = node2
root.right = node3
node2.left = node4
node2.right = node5
node3.left = node6
node3.right = node7
//  二叉树结构:
//        1
//       / \
//     /     \
//   2        3
//  / \      / \
// 4   5    6    7

前序遍历

利用栈结构实现,左子树后入先出

var preorderTraversal = function(root) {
    if(!root) {
        return []
    }
    let result = [],
        stack = [root]
    while(stack.length) {
        // 弹栈顺序:中->左->右
        let curr = stack.pop()
        result.push(curr.val)
        if(curr.right) {
            stack.push(curr.right)
        }
        if(curr.left) {
            stack.push(curr.left)
        }
    }
    return result
};
console.log(preorderTraversal(root))
// 结果: [ 1, 2, 4, 5, 3, 6, 7 ]

中序遍历

继续利用栈结构实现,先对左子树入栈直至左子树为空,然后弹出节点,开始对右子树入栈

var inorderTraversal = function(root) {
    if(!root) {
        return []
    }
    let result = [],
        stack = []
    while(stack.length || root) {
        // 弹栈顺序:左->中->右
        if(root) {
            stack.push(root)
            root = root.left
        } else {
            let curr = stack.pop()
            result.push(curr.val)
            root = curr.right
        }
    }
    return result
};
console.log(inorderTraversal(root))
// 结果: [ 4, 2, 5, 1, 6, 3, 7 ]

后序遍历

利用前序遍历实现的思路,先对左子树入栈,后对右子树入栈,即以中->右->左顺序弹栈,将其遍历结果逆转即是后序遍历的结果

var postorderTraversal = function(root) {
	if(!root) {
		return []
	}
	let result = [],
		stack = [root]
	while(stack.length) {
		// 弹栈顺序:中->右->左
		// 逆转:左->右->中
		let curr = stack.pop()
		result.push(curr.val)
		if(curr.left) {
			stack.push(curr.left)
		}
		if(curr.right) {
			stack.push(curr.right)
		}
	}
	return result.reverse()
};
console.log(postorderTraversal(root))
// 结果: [ 4, 5, 2, 6, 7, 3, 1 ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值