104. Maximum Depth of Binary Tre

2016-11-17  本文已影响51人  hyhchaos

C++

/**
 * Definition for a binary tree node.
 * 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;
    if(root->left!=NULL||root->right!=NULL)
    return max(maxDepth(root->left),maxDepth(root->right))+1;
    else
    return 1;
    }
};

Java

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int maxDepth(TreeNode root) {
    if(root==null) return 0;
    if(root.left!=null||root.right!=null)
    return Math.max(maxDepth(root.left),maxDepth(root.right))+1;
    else return 1;
    }
}

Javascript

/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number}
 */
var maxDepth = function(root) {
    if(root===null) return 0;
    if(root.left!==null||root.right!==null)
    {
    var leftHeight=maxDepth(root.left);
    var rightHeight=maxDepth(root.right);
    return leftHeight>rightHeight? leftHeight+1:rightHeight+1;
    }
    else
    return 1;
};

最优解

思路一样,写法比较简洁

Java

public class Solution {
    public int maxDepth(TreeNode root) {
        if(root==null){
            return 0;
        }
        return 1+Math.max(maxDepth(root.left),maxDepth(root.right));
    }
}
上一篇 下一篇

猜你喜欢

热点阅读