N

(Leet Code c++)Binary Tree Postorder Traversal 본문

Leet Code 알고리즘

(Leet Code c++)Binary Tree Postorder Traversal

naeunchan 2021. 7. 19. 09:41
728x90
반응형

145. Binary Tree Postorder Traversal

 

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]

 

Constraints:

  • The number of the nodes in the tree is in the range [0, 100].
  • -100 <= Node.val <= 100

 

이진 트리의 후위 탐색.

순서는 왼쪽 자식 노드 -> 오른쪽 자식 노드 -> 현재 노드 순서로 방문하여 Treenode에 있는 val을 answer 벡터에 담아주면 된다.

/**
 * 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:
    void postorder(TreeNode * node, vector<int> &answer){
        if(node->left != NULL){
            postorder(node->left, answer);
        }
        
        if(node->right != NULL){
            postorder(node->right, answer);
        }
        
        answer.push_back(node->val);
    }
    
    vector<int> postorderTraversal(TreeNode* root) {
        vector<int> answer;
        
        if(root != NULL){
            postorder(root, answer);
        }
        
        return answer;
    }
};
728x90
반응형