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;
        }
    }
    
  • 相关阅读:
    电路学习实战分析之mos-2
    我这博客咋分类的?
    学习shell之后,实战分析
    二叉树,二叉排序树,红黑树 学习
    哈希表 学习
    《转》C语言可变参函数的实现
    Linux工具记录
    苏州之旅有感
    git 命令动画学
    软件工程相关博客
  • 原文地址:https://www.cnblogs.com/CodingXu-jie/p/13914893.html
Copyright © 2011-2022 走看看