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

    题目:

    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.

    题意及分析:找出一棵树的高度,即最深子节点。使用深度遍历的方法即可,用一个变量记录遍历到当前点的最大高度,然后当前点若有子节点,遍历到子节点,那么该点的高度+1和当前的最大高度大的那个值为的当前点的子节点的最大高度。

    代码:

    /**
     * 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;
            int[] maxDep=new int[1];
            maxDep[0]=1;
            max(maxDep,root,1);
            return maxDep[0];
        }
    
        public void max(int[] maxDep,TreeNode node,int height){
            if(node.left!=null){
                maxDep[0]=Math.max(height+1,maxDep[0]);
                max(maxDep,node.left,height+1);
            }
            if(node.right!=null){
                maxDep[0]=Math.max(height+1,maxDep[0]);
                max(maxDep,node.right,height+1);
            }
        }
    }
  • 相关阅读:
    List,Set,Map初级学习
    String,StringBuffer,StringBuilder 的使用
    activity跳转
    JSON与List之间的转换
    子线程更新UI
    数据库查询关键字显示所有结果
    Java数据类型转换1
    git 操作
    MySql导出表结构
    springBoot双数据源配置
  • 原文地址:https://www.cnblogs.com/271934Liao/p/7197516.html
Copyright © 2011-2022 走看看