二叉树的后序遍历

来源:互联网 发布:笔记本网络驱动 编辑:程序博客网 时间:2024/05/18 07:55

1.问题描述

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

样例

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

   1    \     2    /   3

返回 [3,2,1]


2.解题思路

运用递归的方式,按先左子树再右子树最后根节点的思想将节点存到一个容器内。

3.代码实现

 /**
 * 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
         vector<int>r;
        postorder(r,root);
        return r;
    }
    void postorder(vector<int>& r,TreeNode*root)
    {
         if(root==NULL)
        return;
        postorder(r,root->left);  
        postorder(r,root->right);
         r.push_back(root->val);
          
    }
};

4.感想

与前序和中序一样,保证所有的节点在一个容器内。

0 0
原创粉丝点击