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 ]
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章