本文主要是介绍【数据结构与算法】先序遍历(前序遍历)的非递归实现,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
回忆一下递归实现
/**
/*** Definition for a binary tree node.* function TreeNode(val, left, right) {* this.val = (val===undefined ? 0 : val)* this.left = (left===undefined ? null : left)* this.right = (right===undefined ? null : right)* }*/
/*** @param {TreeNode} root* @return {number[]}*/*/var preorderTraversal = function(root) {var retArr = []if (!root) return retArrvar helpFunc = (r) => {if (!r)return retArr.push(r.val)if (r.left) { helpFunc(r.left) }if (r.right) { helpFunc(r.right)}}helpFunc(root)return retArr
}
用模拟栈来实现
var preorderTraversal = function(root) {var retArr = []if (!root) return retArrvar stack = []stack.push(root)while(stack.length !== 0) {var popE = stack.pop()retArr.push(popE.val)if (popE.right) {stack.push(popE.right)}if (popE.left) {stack.push(popE.left)}}return retArr
}
这篇关于【数据结构与算法】先序遍历(前序遍历)的非递归实现的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!