您的位置:首页 > Web前端 > JavaScript

[LeetCode][JavaScript]Binary Tree Preorder Traversal

2015-09-13 22:56 651 查看

Binary Tree Preorder Traversal

Given a binary tree, return the preorder traversal of its nodes' values.

For example:
Given binary tree
{1,#,2,3}
,

1
\
2
/
3


return
[1,2,3]
.

Note: Recursive solution is trivial, could you do it iteratively?

https://leetcode.com/problems/binary-tree-preorder-traversal/

树的先序遍历,不递归的方式,维护一个栈,先塞右子树,再塞左子树。

Binary Tree Inorder Traversal:

/article/7171024.html

Binary Tree Postorder Traversal:

/article/7171025.html

递归:

/**
* 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 res = [];
preorder(root);
return res;

function preorder(node){
if(node && node.val !== undefined){
res.push(node.val);
if(node.left !== null){
preorder(node.left);
}
if(node.right !== null){
preorder(node.right);
}
}
}
};


非递归:

/**
* @param {TreeNode} root
* @return {number[]}
*/
var preorderTraversal = function(root) {
var stack = [], res = [], curr;
if(root){
stack.push(root);
}
while(stack.length !== 0){
curr = stack.pop();
res.push(curr.val);
if(curr.right !== null){
stack.push(curr.right);
}
if(curr.left !== null){
stack.push(curr.left);
}
}
return res;
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: