97. 두 갈래 나무의 최대 깊이

652 단어
제목: 두 갈래 나무를 정해 최대 깊이를 찾아라.
두 갈래 나무의 깊이는 뿌리 노드에서 가장 먼 잎 노드까지의 거리다.
예제:
다음과 같은 두 갈래 나무를 제시한다.
  1
 / \ 
2   3
   / \
  4   5

이 두 갈래 나무의 최대 깊이는3이다.
코드:
class Solution {
public:
    /**
     * @param root: The root of binary tree.
     * @return: An integer
     */
    int maxDepth(TreeNode *root) {
        // write your code here
        if(root==NULL)return 0;
        int leftDepth=maxDepth(root->left)+1;
        int rightDepth=maxDepth(root->right)+1;
        return max(leftDepth, rightDepth);
    }
};
소감: 이 문제는 매우 간단합니다. 한 걸음에 돌아가 좌우 깊이가 가장 큰 +1으로 돌아가면 됩니다.

좋은 웹페이지 즐겨찾기