欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2022-05-20 13:52:56
...

题目描述:

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);
    }
};

(*^▽^*)