• 平衡二叉树


    题目描述

    输入一棵二叉树,判断该二叉树是否是平衡二叉树。
    /*
    public class TreeNode
    {
        public int val;
        public TreeNode left;
        public TreeNode right;
        public TreeNode (int x)
        {
            val = x;
        }
    }*/

    分析:通过计算左右子树的高度差的绝对值来判断是否为平衡二叉树
    常规思路:从根节点开始,求根左右子树高度,如果高度差大于1,返回false;否则递归判断左右子树是否满足条件
    class Solution
    {
       bool isBalance=true;
        public bool IsBalanced_Solution(TreeNode pRoot)
        {
            if(pRoot==null)
                return true;
            else if(System.Math.Abs(TreeDepth(pRoot.left)-TreeDepth(pRoot.right))>1)
                return false;
            else
                return IsBalanced_Solution(pRoot.left)&&IsBalanced_Solution(pRoot.right);  
        }
        public int TreeDepth(TreeNode root)
        {
            if(root==null) return 0;
            return System.Math.Max(TreeDepth(root.left), TreeDepth(root.right))+1;
        }
    }
    另解:常规思路重复的计算子树的高度。可以用后序遍历,从下到上遍历如果子树中任一不满足条件返回 false,否则返回 true 这样每个节点的高度只会算一次。
    class Solution
    {
        bool isBalanced=true;
        
        public int GetHeight(TreeNode pRoot)
        {
            if(pRoot==null)
                return 0;
            else
            {
                int left=GetHeight(pRoot.left);
                int right=GetHeight(pRoot.right);
                if(System.Math.Abs(left-right)<=1)
                    isBalanced=true;
                else
                    isBalanced=false;
                return left>right?left+1:right+1;
            }
        }
        
        public bool IsBalanced_Solution(TreeNode pRoot)
        {
            GetHeight(pRoot);
            return isBalanced;
        }
    }
    复习回顾知识点:
    <C#中Math>
    Math.Ceil() 向上进位取整;Math.RoundToInt() 四舍五入到整数
    Math.Round() 四舍五入;Math.Abs() 取绝对值
    System.Math.Max(a,b) a,b中较大数;System.Math.Min(a,b) a,b中较小数
    Math.Log(a,b) 以b为底a的对数;Math.Sin(a) 弧度为a的正弦值
    Math.PI π的数值;Math.E e的数值
     
  • 相关阅读:
    flock对文件锁定读写操作的问题 简单
    hdu 2899 Strange Fuction(二分)
    hdu 2199 Can you solve this equation? (二分)
    poj 3080 Blue Jeans (KMP)
    poj 2823 Sliding Window (单调队列)
    poj 2001 Shortest Prefixes (trie)
    poj 2503 Babelfish (trie)
    poj 1936 All in All
    hdu 3507 Print Article (DP, Monotone Queue)
    fzu 1894 志愿者选拔 (单调队列)
  • 原文地址:https://www.cnblogs.com/sherryke/p/10202398.html
Copyright © 2020-2023  润新知