zoukankan      html  css  js  c++  java
  • 【剑指offer】面试题 55. 二叉树的深度

    面试题 55. 二叉树的深度

    题目一:二叉树的深度

    题目描述:输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。   
    

    Java 实现

    /**
     * Definition of TreeNode:
     * public class TreeNode {
     *     public int val;
     *     public TreeNode left, right;
     *     public TreeNode(int val) {
     *         this.val = val;
     *         this.left = this.right = null;
     *     }
     * }
     */
    
    public class Solution {
        /**
         * @param root: The root of binary tree.
         * @return: An integer
         */
        public int maxDepth(TreeNode root) {
            // write your code here
            if (root == null)
                return 0;
            if (root.left == null) {
                return maxDepth(root.right) + 1;
            }
            if (root.right == null) {
                return maxDepth(root.left) + 1;
            }
            return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
        }
    }
    

    题目二:平衡二叉树

    题目描述:给定一个二叉树,确定它是高度平衡的。对于这个问题,一棵高度平衡的二叉树的定义是:一棵二叉树中每个节点的两个子树的深度相差不会超过1。
    

    样例
    平衡二叉树左右子树高度差不超过 1。

    Java 实现

    /**
     * Definition of TreeNode:
     * public class TreeNode {
     *     public int val;
     *     public TreeNode left, right;
     *     public TreeNode(int val) {
     *         this.val = val;
     *         this.left = this.right = null;
     *     }
     * }
     */
    
    public class Solution {
        /**
         * @param root: The root of binary tree.
         * @return: True if this Binary tree is Balanced, or false.
         */
        public boolean isBalanced(TreeNode root) {
            // write your code here
            if(root==null)
                return true;
            int left = maxDepth(root.left);
            int right = maxDepth(root.right);
            if(Math.abs(left-right)>1){
                return false;
            }
            return isBalanced(root.left)&&isBalanced(root.right);
        }
        public int maxDepth(TreeNode node){
            if(node==null)
                return 0;
            return Math.max(maxDepth(node.left),maxDepth(node.right))+1;
        }
    }
    
  • 相关阅读:
    可伸缩的菜单
    Microsoft.AspNet.Identity: UserID用整型数据表示, 而不是GUID
    需要了解的技术
    微信公众号开发一些链接
    SQL Server Connection Strings for ASP.NET Web Applications https://msdn.microsoft.com/en-us/library/jj653752.aspx
    ASP.NET MVC 4 (三) 过滤器
    quick Cocos 2dx 学习网站
    获取SQL server 中的表和说明
    在 fragment 里面调用 findViewById
    gravity 和 layout_gravity
  • 原文地址:https://www.cnblogs.com/hgnulb/p/9029729.html
Copyright © 2011-2022 走看看