leetcode: binary-tree-postorder-traversal:后序遍历二叉树

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Qiana_/article/details/81782729

题目描述:

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?

题目解析:

和后序遍历过程一样,不同的是,为了保证在递归的时候,vector中的值也更新,需要将vector以传引用的方式传给一个函数,这个函数实现真正的后序遍历。

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> postorderTraversal(TreeNode *root) {
        vector<int> vec;
        if(root == NULL)
            return vec;
        _postOrder(root,vec);
        return vec;
    }
    
    void _postOrder(TreeNode* root,vector<int>& ret)
    {
        if(root == NULL)
            return;
        _postOrder(root->left,ret);
        _postOrder(root->right,ret);
        ret.push_back(root->val);
    }
};

(*^▽^*)

猜你喜欢

转载自blog.csdn.net/Qiana_/article/details/81782729
今日推荐