码迷,mamicode.com
首页 > 编程语言 > 详细

[LeetCode][JavaScript]Binary Tree Preorder Traversal

时间:2015-09-14 00:17:57      阅读:187      评论:0      收藏:0      [点我收藏+]

标签:

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/

 

 


 

 

 

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

递归:

 1 /**
 2  * Definition for a binary tree node.
 3  * function TreeNode(val) {
 4  *     this.val = val;
 5  *     this.left = this.right = null;
 6  * }
 7  */
 8 /**
 9  * @param {TreeNode} root
10  * @return {number[]}
11  */
12 var preorderTraversal = function(root) {
13     var res = [];
14     preorder(root);
15     return res;
16 
17     function preorder(node){
18         if(node && node.val !== undefined){
19             res.push(node.val);
20             if(node.left !== null){
21                 preorder(node.left);
22             }
23             if(node.right !== null){
24                 preorder(node.right);
25             }
26         }
27     }
28 };

 

非递归:

 1 /**
 2  * @param {TreeNode} root
 3  * @return {number[]}
 4  */
 5 var preorderTraversal = function(root) {
 6     var stack = [], res = [], curr;
 7     if(root && root.val !== undefined){
 8         res.push(root.val);
 9         if(root.right !== null){
10             stack.push(root.right);
11         }
12         if(root.left !== null){
13             stack.push(root.left);
14         }
15     }
16     while(stack.length !== 0){
17         curr = stack.pop();
18         res.push(curr.val);
19         if(curr.right !== null){
20             stack.push(curr.right);
21         }
22         if(curr.left !== null){
23             stack.push(curr.left);
24         }
25     }
26     return res;
27 };

 

 

[LeetCode][JavaScript]Binary Tree Preorder Traversal

标签:

原文地址:http://www.cnblogs.com/Liok3187/p/4805834.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!