码迷,mamicode.com
首页 > 其他好文 > 详细

Binary Tree Postorder Traversal <leetcode>

时间:2014-09-07 14:44:25      阅读:208      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   color   os   io   ar   strong   for   

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?

思路:1、非递归遍历  2、递归遍历

非递归:

 

 1 /**
 2  * Definition for binary tree
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10  
11  struct node{
12      TreeNode *root;
13      bool isFirst;
14  };
15  
16 class Solution {
17 public:
18     vector<int>  result;
19     vector<int> postorderTraversal(TreeNode *root) {
20              vector<node>  str;
21              if(root==NULL)  return result;
22              TreeNode *p=root;
23              while(p!=NULL||str.size()!=0)
24              {
25                  while(p!=NULL)
26                  {
27                      node n;
28                      n.isFirst=true;
29                      n.root=p;
30                      str.push_back(n);
31                      p=p->left;
32                  }
33                  if(str.size()!=0)
34                  {
35                      node temp=str.back();
36                      str.pop_back();
37 
38                      if(temp.isFirst==true)
39                      {
40                          temp.isFirst=false;
41                          str.push_back(temp);
42                          p=temp.root->right;
43                      }
44                      else
45                      {
46                          result.push_back(temp.root->val);
47                          p=NULL;
48                      }
49                      
50                  }
51              }
52              return result;
53     }
54 };

 

 

2:递归

 

 1 /**
 2  * Definition for binary tree
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10  
11 class Solution {
12 public:
13     vector<int>  result;
14     vector<int> postorderTraversal(TreeNode *root) {
15         digui(root);
16         return result;
17     }
18     
19     void digui(TreeNode *root)
20     {
21         if(root!=NULL)
22         {
23             digui(root->left);
24             digui(root->right);
25             result.push_back(root->val);
26         }
27     }
28 };

 

Binary Tree Postorder Traversal <leetcode>

标签:des   style   blog   color   os   io   ar   strong   for   

原文地址:http://www.cnblogs.com/sqxw/p/3960377.html

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