zoukankan      html  css  js  c++  java
  • [LeetCode]104. Maximum Depth of Binary Tree

    题目描述:

    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.

    思路:

    求二叉树的最大深度。递归和迭代两种解法。
    递归:如果根节点是null,则返回0
    否则返回左子树或者右子树的深度+1

    迭代:未做。

    /*

    public class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int x) { val = x; }

    */

     1 public class Solution104 {
     2     public int maxDepth(TreeNode root) {
     3         if(root == null) return 0;
     4         return Math.max(maxDepth(root.left),maxDepth(root.right))+1;
     5     }
     6     public static void main(String[] args) {
     7         // TODO Auto-generated method stub
     8         Solution104 solution104 = new Solution104();
     9         TreeNode root = new TreeNode(1);
    10         root.left = new TreeNode(2);
    11         root.right = new TreeNode(2);
    12         root.left.left = new TreeNode(3);
    13         root.left.right = new TreeNode(4);
    14         root.right.left = new TreeNode(4);
    15         //root.right.right = new TreeNode(3);
    16         root.right.left.left = new TreeNode(4);
    17         System.out.println(solution104.maxDepth(root));
    18     }
    19 
    20 }
  • 相关阅读:
    c#线程带参数
    svn自动update到指定目录
    204. 计数质数
    178. 分数排名
    387. 字符串中的第一个唯一字符
    374. 猜数字大小
    371. 两整数之和
    350. 两个数组的交集 II
    326. 3的幂
    219. 存在重复元素 II
  • 原文地址:https://www.cnblogs.com/zlz099/p/8184763.html
Copyright © 2011-2022 走看看