Leetcode 104: Maximum Depth of Binary Tree

问题描述

在这里插入图片描述

java实现

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
//way1
class Solution {
    //递归  分治的思想
    public int maxDepth(TreeNode root) {
        int depth=0;
        if(root==null)
            return depth;
        //分
        int depthLeft=0;
        int depthRight=0;
        if(root.left!=null)
            depthLeft=maxDepth(root.left);
        if(root.right!=null)
            depthRight=maxDepth(root.right);
        //合
        return Math.max(depthLeft,depthRight)+1;
    }
}

// //way2
// class Solution {
//     //递归  遍历的思想
//     private int depth;
//     public int maxDepth(TreeNode root) {
//         depth = 0;
//         int depthLeft = 0;
//         helper(root,1);
//         return depth;
//     }
//     private void helper(TreeNode node,int currentDepth){
//         if(node==null)
//             return;
//         if(currentDepth>depth)
//             depth=currentDepth;
//         helper(node.left,currentDepth+1);
//         helper(node.right,currentDepth+1);
//     }
// }
发布了172 篇原创文章 · 获赞 22 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_44135282/article/details/103827859