回忆一下递归实现
javascript
/**
/**
* 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 retArr
var 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
}
用模拟栈来实现
javascript
var preorderTraversal = function(root) {
var retArr = []
if (!root) return retArr
var 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
}