LeetCode145. Binary Tree Postorder Traversal(hard)

来源:互联网 发布:poe交换机端口不供电 编辑:程序博客网 时间:2024/06/06 11:43

原题地址:https://leetcode.com/problems/binary-tree-postorder-traversal/description/


题目:
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].


题解:
单纯的后序遍历,只需再写一个函数进行按后序遍历顺序递归即可


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

67 / 67 test cases passed.
Status: Accepted
Runtime: 3 ms

阅读全文
0 0
原创粉丝点击