求二叉樹的最大深度和最小深度以及之間的差

來源:互聯網
上載者:User
maxheight函數就是求二叉樹的左子樹與右子樹中那個深度最大最大深度多少,minheight函數就是求二叉樹的左子樹與右子樹中那個深度最小最小深度多少,Isbalance函數就是求左子樹與右子樹的深度差,只要不大於1就是平衡二叉樹。平衡二叉樹:它是一 棵空樹或它的左右兩個子樹的高度差的絕對值不超過1,並且左右兩個子樹都是一棵平衡二叉樹。        static void Main(string[] args)        {            Node root = new Node();            Node c1 = new Node();            Node c2 = new Node();            root.left = c1;            root.right = c2;            Node c11 = new Node();            c1.left = c11;            Node c112 = new Node();            c11.right = c112;            Program p = new Program();            Console.WriteLine(p.isBalanced(root));            Console.Read();        }        public int GetMaxHeight(Node root)        {            if (root == null)                return 0;            int max = 1 + Math.Max(this.GetMaxHeight(root.left), this.GetMaxHeight(root.right));            return max;        }        public int GetMinHeight(Node root)        {            if (root == null)                return 0;            int min = 1 + Math.Min(this.GetMinHeight(root.left), this.GetMinHeight(root.right));            return min;        }        public bool isBalanced(Node root)        {            int max = this.GetMaxHeight(root);            int min = this.GetMinHeight(root);            if (max - min > 1)                return false;            else                return true;        }    }    public class Node    {        public int value;        public Node left;        public Node right;    } 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.