zoukankan      html  css  js  c++  java
  • [Leetcode 104](二叉树的最大深度)

    Leetcode 104 二叉树的最大深度

    数据结构定义:

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    

    自顶向下写法:

    class Solution {
        int result = 0;
        public int maxDepth(TreeNode root) {
            maxDepthHelper(root,1);
            return result;
        }
    
        private void maxDepthHelper(TreeNode root,int depth){
            if(root == null){
                return;
            }
            result = Math.max(result,depth);
            maxDepthHelper(root.left,depth +1);
            maxDepthHelper(root.right,depth +1);
        } 
    }
    

    自低向上写法:

    class Solution {
        public int maxDepth(TreeNode root) {
            if(root == null){
                return 0;
            }
            int leftDepth = maxDepth(root.left);
            int rightDepth = maxDepth(root.right);
            return Math.max(leftDepth,rightDepth) +1;
        }
    }
    

    广度优先遍历写法:

    class Solution {
        public int maxDepth(TreeNode root) {
            int result = 0;
            if(root == null){
                return result;
            }
            Queue<TreeNode> queue =new LinkedList<>();
            queue.offer(root);
            while(!queue.isEmpty()){
                int size = queue.size();
                while(size > 0){
                    TreeNode node =queue.poll();
                    if(node.left != null){
                        queue.offer(node.left);
                    }
                    if(node.right != null){
                        queue.offer(node.right);
                    }
                    size --;
                }
                result ++;
            }
            return result;
        }
    }
    

    其他技巧:

    class Solution {
        public int maxDepth(TreeNode root) {
            return root ==null ? 0 : Math.max(maxDepth(root.left),maxDepth(root.right)) +1;
        }
    }
    
  • 相关阅读:
    mac 安装 pycharm
    mac clion c/c++环境配置
    CLion201914 下载安装
    mac 安装cmake
    JetBrains CLion 2019 for Mac(智能C和C++编辑器)中英文如何切换完整教程
    SnippetsLab Mac 代码收藏管理工具
    goland 安装破解
    linux管道pipe详解
    HTML meta pragma no-cache 页面缓存
    Connection: close
  • 原文地址:https://www.cnblogs.com/CodingXu-jie/p/13914893.html
Copyright © 2011-2022 走看看