-
[LeetCode] 145. Binary Tree Postorder Traversal c++Coding Test/LeetCode 2022. 12. 22. 18:12728x90
- 문제
Given the root of a binary tree, return the postorder traversal of its nodes' values.
Input: root = [1,null,2,3] Output: [3,2,1]
- 문제 해결
vector<int> postorderTraversal(TreeNode* root) { stack<TreeNode*> stk; if(root){ stk.push(root); } vector<int> ans; while(stk.size()){ auto p = stk.top(); if(p == nullptr){ stk.pop(); ans.push_back(stk.top()->val); stk.pop(); continue; } stk.push(nullptr); if(p->right){ stk.push(p->right); } if(p->left){ stk.push(p->left); } } return ans; }
다른 방법
class Solution { private: void postorder(TreeNode* curr, vector<int>& vec){ if(!curr){ return; } postorder(curr->left, vec); postorder(curr->right, vec); vec.push_back(curr->val); return; } public: vector<int> postorderTraversal(TreeNode* root) { vector<int> vec; postorder(root, vec); return vec; } };
728x90'Coding Test > LeetCode' 카테고리의 다른 글
[LeetCode] 189. Rotate Array c++ (0) 2022.12.23 [LeetCode] 977. Squares of a Sorted Array c++ (0) 2022.12.23 [LeetCode] 872. Leaf-Similar Trees c++ (0) 2022.12.22 [LeetCode] 965. Univalued Binary Tree c++ (0) 2022.12.22 [LeetCode] 463. Island Perimeter c++ (0) 2022.12.22