-
[LeetCode] Maximum Depth of Binary Tree (C++)알고리즘 문제풀이/LeetCode 2021. 3. 6. 18:10
leetcode.com/problems/maximum-depth-of-binary-tree/
역시나 리스트를 사용해 포인터의 개념이 필요했습니다. 트리의 DFS, BFS 탐색을 해보는 문제였습니다.
/** * 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) {} * }; */ /* DFS(Depth First Search) */ class Solution { public: int maxDepth(TreeNode* root) { if(root == NULL) return 0; return max(maxDepth(root->left), maxDepth(root->right)) + 1; } };
/** * 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) {} * }; */ /* BFS(Breadth First Search) */ class Solution { public: int maxDepth(TreeNode* root) { if(root == NULL) return 0; int answer; queue<pair<TreeNode*, int > > q; // root, level을 저장 q.push({ root, 1 }); while(!q.empty()) { TreeNode* now = q.front().first; int cnt = q.front().second; answer = cnt; q.pop(); if(now->left != NULL) q.push({ now->left, cnt + 1 }); if(now->right != NULL) q.push({ now->right, cnt + 1 }); } return answer; } };
'알고리즘 문제풀이 > LeetCode' 카테고리의 다른 글
[LeetCode] Min Stack (C++) (0) 2021.03.10 [LeetCode] Linked List Cycle (C++) (0) 2021.03.09 [LeetCode] Merge Two Sorted Lists (C++) (0) 2021.03.04 [LeetCode/easy] Single Number (C++) (0) 2021.02.08 [LeetCode/easy] Symmentric-Tree (C++) (0) 2021.02.08