68 二叉树的后序遍历

原题网址:http://www.lintcode.com/zh-cn/problem/binary-tree-postorder-traversal/

给出一棵二叉树,返回其节点值的后序遍历。

样例

给出一棵二叉树 {1,#,2,3},

   1
    
     2
    /
   3

返回 [3,2,1]

挑战 

你能使用非递归实现么?

标签 
 
一、递归
 1 /**
 2  * Definition of TreeNode:
 3  * class TreeNode {
 4  * public:
 5  *     int val;
 6  *     TreeNode *left, *right;
 7  *     TreeNode(int val) {
 8  *         this->val = val;
 9  *         this->left = this->right = NULL;
10  *     }
11  * }
12  */
13 
14 class Solution {
15 public:
16     /**
17      * @param root: A Tree
18      * @return: Postorder in ArrayList which contains node values.
19      */
20      vector<int> result;
21     vector<int> postorderTraversal(TreeNode * root) {
22         // write your code here
23             if (root!=NULL)
24     {
25         postorderTraversal(root->left);
26         postorderTraversal(root->right);
27         result.push_back(root->val);
28     }
29     return result;
30     }
31 };

二、非递归

遍历时若当前节点挂载着左右子树,子树依旧照着左右根的顺序遍历。

参考:https://blog.csdn.net/u010510962/article/details/51180443

 采用栈,一种更简便的思想是:后序遍历,左节点先于右结点先于根节点被访问,因此,根先入栈,出栈时访问节点。若当前栈顶结点没有左孩子和右孩子或者左孩子节点和右孩子结点都被访问了,则直接访问当前栈顶结点。否则,当前栈顶结点、存在左孩子或右孩子,则依照先入右孩子结点,再入左孩子结点的顺序入栈。

 1 /**
 2  * Definition of TreeNode:
 3  * class TreeNode {
 4  * public:
 5  *     int val;
 6  *     TreeNode *left, *right;
 7  *     TreeNode(int val) {
 8  *         this->val = val;
 9  *         this->left = this->right = NULL;
10  *     }
11  * }
12  */
13 
14 class Solution {
15 public:
16     /**
17      * @param root: A Tree
18      * @return: Postorder in ArrayList which contains node values.
19      */
20     vector<int> postorderTraversal(TreeNode * root) {
21         // write your code here
22         vector<int> result;
23     if (root==NULL)
24     {
25         return result;
26     }
27     stack<TreeNode*> temp;
28     TreeNode *cur=root;
29     TreeNode *pre=NULL;
30     temp.push(root);
31 
32     while(!temp.empty())
33     {
34         cur=temp.top();
35         if ((cur->left==NULL&&cur->right==NULL)||(pre!=NULL)&&(pre==cur->left||pre==cur->right))
36         {                                                     //这里用||而不是直接判断是否为右孩子是防止某个节点右孩子为空?;
37             result.push_back(cur->val);
38             pre=cur;
39             temp.pop();
40         }
41         else  //入栈顺序根右左,保证遍历时(出栈)每个三点子树顺序为左右根;
42         {
43             if (cur->right!=NULL)
44             {
45                 temp.push(cur->right);
46             }
47             if (cur->left!=NULL)
48             {
49                 temp.push(cur->left);
50             }
51         }
52     }
53 
54     return result;
55     }
56 };

 另一种思路: https://blog.csdn.net/chan15/article/details/48833949

PS:没怎么看懂,改天研究下

原文地址:https://www.cnblogs.com/Tang-tangt/p/8748886.html