for Robot Artificial Inteligence

27. Maximum Depth of Binary Tree

|

/**
 * 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:
    int maxDepth(TreeNode* root) {
        return (root==NULL)?0:max(maxDepth(root->left),maxDepth(root->right))+1; // 동시에 확인

    }
};
  • Tree 문제는 대부분 Recursive로 해결한다.
  • iteration로 풀떄는 queue를 이용한다.

Comments