zoukankan      html  css  js  c++  java
  • Maximum Depth of Binary Tree

    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.

    分析:用层次遍历,记录下访问深度即可。参考 http://www.cnblogs.com/baichangfu/p/7461433.html

    JAVA CODE

    /**
     * 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) {
            int deep = 0;
            Queue<TreeNode> queue = new ArrayDeque<>();
            Queue<Integer> queue1 = new ArrayDeque<>();
            if(root!=null){
                queue.offer(root);
                queue1.offer(new Integer(deep++));
            }
            while(!queue.isEmpty()){
                root = queue.poll();
                int hh = queue1.poll().intValue();
                if(deep == hh){
                    deep++;
                }
                if(root.left!=null){
                    queue.offer(root.left);
                    queue1.offer(new Integer(deep));
                }
                if(root.right!=null){
                    queue.offer(root.right);
                    queue1.offer(new Integer(deep));
                }
            }
            return deep;
        }
    }
  • 相关阅读:
    2019hdu多校1
    codefroce842C
    [codeforce686D]树的重心
    [codeforce1188C&D]
    Educational Codeforces Round 66
    [hdu4343]interval query
    Luogu 4234 最小差值生成树
    BZOJ 2594 水管局长
    Luogu 2173 [ZJOI2012]网络
    Luogu 2147 洞穴勘测
  • 原文地址:https://www.cnblogs.com/baichangfu/p/7468706.html
Copyright © 2011-2022 走看看