Easy
Related Topics: Stack / Tree / Depth-First Search / Binary Tree
LeetCode Source
就是一般的後序尋訪二元樹
透過遞迴解法完成
Time Complexity: O(n)
Space Complexity: O(n)
class Solution:
def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
self.res = []
self.post(root)
return self.res
def post(self, root):
if root == None:
return
self.post(root.left)
self.post(root.right)
self.res.append(root.val)
class Solution {
private:
vector<int> res;
public:
vector<int> postorderTraversal(TreeNode* root) {
post(root);
return res;
}
void post(TreeNode* root) {
if (root == nullptr)
return;
post(root->left);
post(root->right);
res.push_back(root->val);
}
};