Given the root of a binary tree, return the postorder traversal of its nodes' values.
Example 1:
Input: root = [1,null,2,3]
Output: [3,2,1]
Example 2:
Input: root = []
Output: []
Example 3:
Input: root = [1]
Output: [1]
Example 4:
Input: root = [1,2]
Output: [2,1]
Example 5:
Input: root = [1,null,2]
Output: [2,1]
想法: 這題和 144. Binary Tree Preorder Traversal 類似直接先用 recursive 解了,有空再練習 iterative 的方式。
完整程式碼:class Solution {public:
vector<int> postorder;
void traverse(TreeNode* root) {
if (root == NULL) { return; }
traverse(root->left);
traverse(root->right);
postorder.emplace_back(root->val);
}
vector<int> postorderTraversal(TreeNode* root) {
traverse(root);
return postorder;
}
};
沒有留言:
張貼留言