/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
var preorderTraversal = function(root) {
var ret = [];
if(root === null){
return ret;
}
var stack = [];
var cur = root;
while(cur!==null){
ret.push(cur.val);
left = cur.left;
right = cur.right;
if(left !== null && right !== null){
stack.push(right);
cur = left;
}else if(left === null && right === null){
if(stack.length>0){
cur = stack.pop();
}else{
cur = null;
}
}else if(left === null){
cur = right;
}else{
cur = left;
}
//console.log(cur);
}
return ret;
};
这道题用递归可以很好的解决,可是题目说是否可以不用递归。
于是就只好利用栈来完成了。
思路也很清晰。