LeetCodeOJ. Maximum Depth of Binary Tree

試題請參見: https://oj.leetcode.com/problems/maximum-depth-of-binary-tree/

題目概述

Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

解題思路

經典數據結構作業題, 當然也是經典的面試題.
思路簡單的說就是遞歸.

源代碼

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int maxDepth(TreeNode *root) {
        if ( root == NULL ) {
            return 0;
        } else {
            int leftDepth = maxDepth(root->left) + 1;
            int rightDepth = maxDepth(root->right) + 1;
            
            return ( leftDepth > rightDepth ? leftDepth : rightDepth );
        }
    }
};


發佈了50 篇原創文章 · 獲贊 1 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章