코딩테스트 준비/leetcode

145. Binary Tree Postorder Traversal

MAKGA 2021. 7. 22. 20:21
320x100

https://leetcode.com/problems/binary-tree-postorder-traversal/

 

Binary Tree Postorder Traversal - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

이진 트리가 주어졌을 때, 모든 노드를 후위 순회(postorder)로 방문한다.

 

/**
 * 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<int> postorderTraversal(TreeNode* root) {
        if (root == nullptr) {
            return v;
        }
        
        if (root->left) {
            postorderTraversal(root->left);
        }
        
        if (root->right) {
            postorderTraversal(root->right);
        }
        
        v.push_back(root->val);
        return v;
    }
private:
    vector<int> v;
};

320x100

'코딩테스트 준비 > leetcode' 카테고리의 다른 글

95. Unique Binary Search Trees II  (0) 2021.07.23
226. Invert Binary Tree  (0) 2021.07.22
1302. Deepest Leaves Sum [Medium]  (0) 2021.07.21
144. Binary Tree Preorder Traversal [Easy]  (0) 2021.07.21
110. Balanced Binary Tree [Easy]  (0) 2021.07.21