美文网首页
104. Maximum Depth of Binary Tre

104. Maximum Depth of Binary Tre

作者: hyhchaos | 来源:发表于2016-11-17 14:25 被阅读51次

    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));
        }
    }
    

    相关文章

      网友评论

          本文标题:104. Maximum Depth of Binary Tre

          本文链接:https://www.haomeiwen.com/subject/gmmdpttx.html