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

[LeetCode][JavaScript]Binary Tree Postorder Traversal

时间:2015-09-19 22:25:13      阅读:194      评论:0      收藏:0      [点我收藏+]

标签:

Binary Tree Postorder Traversal

Given a binary tree, return the postorder traversal of its nodes‘ values.

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

   1
         2
    /
   3

 

return [3,2,1].

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

 

 

 


 

 

同样的配方,同样的味道。

Binary Tree Inorder Traversal:

http://www.cnblogs.com/Liok3187/p/4808974.html

Binary Tree Preorder Traversal:

http://www.cnblogs.com/Liok3187/p/4805834.html

 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 postorderTraversal = function(root) {
13     var stack = [], res = [], top;
14     if(root){
15         stack.push(root);
16     }
17 
18     while(stack.length !== 0){
19         top = stack.pop();
20         if(typeof top === "number"){
21             res.push(top);
22         }else{
23             stack.push(top.val);
24             if(top.right){
25                 stack.push(top.right);
26             }
27             if(top.left){
28                 stack.push(top.left);
29             }
30         }
31     }
32     return res;
33 };

 

[LeetCode][JavaScript]Binary Tree Postorder Traversal

标签:

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

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