zoukankan      html  css  js  c++  java
  • 104 Maximum Depth of Binary Tree 二叉树的最大深度

    给定一个二叉树,找出其最大深度。
    二叉树的深度为根节点到最远叶节点的最长路径上的节点数。
    案例:
    给出二叉树 [3,9,20,null,null,15,7],
        3
       /
      9  20
        / 
       15   7
    返回最大深度为 3 。
    详见:https://leetcode.com/problems/maximum-depth-of-binary-tree/description/

    Java实现:

    递归实现:

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        public int maxDepth(TreeNode root) {
            if(root==null){
                return 0;
            }
            int left=maxDepth(root.left);
            int right=maxDepth(root.right);
            return left>right?left+1:right+1;
        }
    }
    

    非递归实现:

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        public int maxDepth(TreeNode root) {
            if(root==null){
                return 0;
            }
            LinkedList<TreeNode> que=new LinkedList<TreeNode>();
            que.offer(root);
            int node=1;
            int level=0;
            while(!que.isEmpty()){
                root=que.poll();
                --node;
                if(root.left!=null){
                    que.offer(root.left);
                }
                if(root.right!=null){
                    que.offer(root.right);
                }
                if(node==0){
                    ++level;
                    node=que.size();
                }
            }
            return level;
        }
    }
    
  • 相关阅读:
    python 多线程测试
    python 多线程join()
    python 多线程 t.setDaemon(True):
    线程锁
    python 多线程
    模板渲染和参数传递.
    求两个数组的交集
    java数组并集/交集/差集(补集)
    java各种集合的线程安全
    页面跳转和重定向
  • 原文地址:https://www.cnblogs.com/xidian2014/p/8718237.html
Copyright © 2011-2022 走看看