递归解法
var result = []
function preorderTraversal( root ) {
// write code here
if(!root){return []}
result.push(root.val)
preorderTraversal(root.left)
preorderTraversal(root.right)
return result
}迭代解法
/*
* function TreeNode(x) {
* this.val = x;
* this.left = null;
* this.right = null;
* }
*/
/**
*
* @param root TreeNode类
* @return int整型一维数组
*/
function preorderTraversal( root ) {
// write code here
var stack = []
var result = []
var current = root
while(current || stack.length){
while(current){
result.push(current.val)
stack.push(current.right)
current = current.left
}
current = stack.pop()
}
return result
}
module.exports = {
preorderTraversal : preorderTraversal
};
京公网安备 11010502036488号