Leetcode Binary Tree Postorder Traversal

xiaoxiao2021-02-28  84

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?

递归大法代码如下:

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

迭代大法代码如下:

转载请注明原文地址: https://www.6miu.com/read-55318.html

最新回复(0)