二叉樹的最大深度-LintCode

描述:

給定一個二叉樹,找出其最大深度。

二叉樹的深度爲根節點到最遠葉子節點的距離。


樣例:

給出一棵如下的二叉樹:

  1
 / \ 
2   3
   / \
  4   5

這個二叉樹的最大深度爲3.


思路:

這個題就是遞歸,不斷返回左右子樹中較大的高度。


代碼:

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */
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 lheight=0, rheight=0;
        
        lheight=maxDepth(root->left);
        rheight=maxDepth(root->right);
        
        if(lheight>rheight)
        return lheight+1;
        else return rheight+1;
        

        
    }
};

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章