[LeetCode 104]Maximum Depth of Binary Tree (easy)

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.

Example
Given a binary tree as follow:

  1
 / \ 
2   3
   / \
  4   5
The maximum depth is 3.

思路1. Top-down

  1. 递归函数maintain2个变量,1) current depth 2) maxDepth.
  2. Base Case:
  • 当前节点为空时,直接返回
  • 如果节点为leaf, 用current depth更新maxDepth
  1. 继续递归其左右子节点,current depth + 1 传入左右子树。

思路2. Bottom-up

  1. 递归函数直接返回current max depth.
  2. Base Case:
  • 当前节点为空时,直接返回0
  1. leftDepth = maxDepth (root.left);
    rightDepth = maxDepth(root.right);
  2. return Math.max (leftDepth, rightDepth) + 1
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    /**************  Top down solution *******************/
    public int maxDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        
        int[] maxDepth = { Integer.MIN_VALUE };
        
        maxDepthHelper (root, 1, maxDepth);
        
        return maxDepth[0];
    }
    
    private void maxDepthHelper (TreeNode root, int depth, int[] maxDepth) {
        if (root == null) {
            return;
        }
        
        if (root.left == null && root.right == null) {
            maxDepth[0] = Math.max (maxDepth[0], depth);
            return;
        }
        
        maxDepthHelper (root.left, depth + 1, maxDepth);
        maxDepthHelper (root.right, depth + 1, maxDepth);
    }
    
    /********************** Top Down End*********************/
    
    
        
    /**************  Bottom Up solution *******************/
    public int maxDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        
        return maxDepthHelper (root);
    }
    
    private int maxDepthHelper (TreeNode root) {
        if (root == null) {
            return 0;
        }
        
        int leftDepth = maxDepthHelper (root.left);
        int rightDepth = maxDepthHelper (root.right);
        
        return Math.max (leftDepth, rightDepth) + 1;
    }
    /**************  Bottom Up END *******************/
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容