zoukankan      html  css  js  c++  java
  • 二叉树最大深度

    http://www.lintcode.com/zh-cn/problem/maximum-depth-of-binary-tree/

    注意点:下面代码不行的,maxDepth传入函数是值传递,不是地址传递,所以它的值是不会变的,最后的值还是0;

        要解决这个问题,可以不把maxDepth作为参数传到函数里; 那就给helper 返回int。

    private int maxDepth = 0;
    public int maxDepth(TreeNode root) {
    if(root == null) return maxDepth;
    helper(root, 0, maxDepth);
    return maxDepth;
    }
    private void helper(TreeNode root, int curDep, int maxDepth) {
    if(root == null) return;
    curDep++;
    if(curDep > maxDepth) maxDepth =curDep;
    helper(root.left,curDep,maxDepth);
    helper(root.right,curDep,maxDepth);
    return;
    }

    //修改如下:

    private int maxDepth = 0;
    public int maxDepth(TreeNode root) {
    if(root == null) return maxDepth;
    return helper(root, 0, maxDepth);

    }
    private int helper(TreeNode root, int curDep, int maxDepth) {
    if(root == null) return maxDepth;
    curDep++;
    if(curDep > maxDepth) maxDepth =curDep;
    int left = helper(root.left,curDep,maxDepth);
    int right = helper(root.right,curDep,maxDepth);
    return Math.max(left, right);
    }

     1 public int maxDepth(TreeNode root) {
     2     int dep = 0;
     3     if(root == null) return dep;
     4     int left = maxDepth(root.left);
     5     int right = maxDepth(root.right);
     6     return Math.max(left,right) + 1;
     7 }
     8 //上一个是分治的思想,下一个是将result作为参数在函数中传递,
     9 //类似二叉树遍历里的traverse。(返回空即可 )
    10 private int dep = 0;
    11 public int maxDepth(TreeNode root) {
    12     helper(root, 0);
    13     return dep;
    14 }
    15 
    16 private void helper(TreeNode root, int currDep) {
    17     if(root == null) return;
    18     currDep++;
    19     if(currDep > dep) dep = currDep;
    20     helper(root.left, currDep);               //       1           
    21     helper(root.right, currDep);              //    2      null   此情况下,left的currDep++,且dep = currDep;
    22                                               //                  而right的currDep没变,也不会影响到dep。
    23                                               //                  如果null换成3,right的currDep++,还是不会影响到dep。
    24 } 
    View Code
  • 相关阅读:
    分享一个MySQL分库分表备份脚本(原)
    mysql配置以及性能优化(转)
    redis 集群配置实战
    Debian安装fail2ban来防止扫描
    关于微信小程序,一些想法
    读书笔记:《HTML5开发手册》-- 现存元素的变化
    linux下如何使用vnstat查看服务器带宽流量统计
    在iOS微信浏览器中自动播放HTML5 audio(音乐)的2种正确方式
    VS自定义项目模板:[4]自定义模板的分组
    VS自定义项目模板:[3]创建自定义模板
  • 原文地址:https://www.cnblogs.com/ddcckkk/p/6823644.html
Copyright © 2011-2022 走看看