LintCode 二叉树的后序遍历

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

样例

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

   1
    
     2
    /
   3

返回 [3,2,1]

分析:后序遍历要比先序,中序要难一些。 后序是左右根。

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */
class Solution {
    /**
     * @param root: The root of binary tree.
     * @return: Postorder in vector which contains node values.
     */
public:
    vector<int> postorderTraversal(TreeNode *root) {
        // write your code here
      TreeNode *curr,*pre;
      vector<int> res;
      stack<TreeNode *>s;
      curr=root;
     do
     {
         while(curr!=NULL)
         {
             s.push(curr);
             curr=curr->left;
         }
         pre=NULL;
         while(!s.empty())
         {
             curr=s.top();
             s.pop();
             if(curr->right==pre)
             {
                 res.push_back(curr->val);
                 pre=curr;
             }
             else
             {
                 s.push(curr);
                 curr=curr->right;
                 break;
             }
         }
     }while(!s.empty());
     return res;
    }
};

  

原文地址:https://www.cnblogs.com/lelelelele/p/6116789.html