Leetcode Problem:
Summary
- Postorder traversal of a binary tree nodes' values
Approach
- Recursive approach with left subtree and right subtree traversals followed by the current node's value.
Complexity
- O(n) where n is the number of nodes in the tree
Explain
- The solution uses a recursive approach to traverse the binary tree
- It first checks if the root is null, if so, it returns an empty vector
- Then, it recursively calls the postorderTraversal function on the left and right subtrees, and combines the results by inserting the right subtree's values into the left vector and appending the current node's value
- This process is repeated until the base case is reached, resulting in a postorder traversal of the tree's nodes' values.
Solution Code:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector postorderTraversal(TreeNode* root) {
if(root==nullptr)
return {};
vector left = postorderTraversal(root->left);
vector right = postorderTraversal(root->right);
left.insert(left.end(), right.begin(), right.end());
left.push_back(root->val);
return left;
}
};
'알고리즘' 카테고리의 다른 글
Clear Digits (0) | 2025.02.10 |
---|---|
N-ary Tree Postorder Traversal (0) | 2025.02.10 |
Find the Closest Palindrome (0) | 2025.02.10 |
Fraction Addition and Subtraction (0) | 2025.02.10 |
Number Complement (0) | 2025.02.10 |