Home LeetCode - 107. Binary Tree Level Order Traversal II
Post
Cancel

LeetCode - 107. Binary Tree Level Order Traversal II

107. Binary Tree Level Order Traversal II - easy

문제

Given a binary tree, return the bottom-up level order traversal of its nodes’ values. (ie, from left to right, level by level from leaf to root).

제한사항

입출력 예

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Given binary tree [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

return its bottom-up level order traversal as:

[
  [15,7],
  [9,20],
  [3]
]

풀이

  • Hash, BFS, Tree
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/**
 * 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<vector<int>> levelOrderBottom(TreeNode* root) {
    if (!root) {
        return {};
    }
    
    std::vector<std::vector<int>> res;
    std::map<int, std::vector<int>> m;
    std::queue<std::pair<TreeNode*, int>> q;
    
    // BFS
    q.push({root, 0});
    while (!q.empty()) {
      auto node = q.front();
      q.pop();
      
      // Map에 해당 level의 vector가 없으면 새로 추가
      m[node.second].push_back(node.first->val);
      
      if (node.first->left) {
        q.push({node.first->left, node.second + 1});
      }
      
      if (node.first->right) {
        q.push({node.first->right, node.second + 1});
      }
    }
    
    // Map에 저장된 key(트리의 level)의 반대순으로 저장
    for (auto iter = m.rbegin() ; iter != m.rend() ; ++iter) {
      res.emplace_back(iter->second);
    }

    return res;
  }
};
}
This post is licensed under CC BY 4.0 by the author.