Ejemplo n.º 1
0
        /// <summary>
        /// Checks if a binary tree is balanced.
        /// 
        /// The definition of balance is with CLRS [1]. Under this definition, a balanced tree is:
        /// 
        /// 1. Left and right subtree are balanced
        /// 2. The left and right trees' height difference is no larger than 1
        /// 
        /// The definition of tree height is with CLRS and Wikipedia [2]. With this definition, the following holds:
        /// 
        /// 1. A single node tree has height 0
        /// 2. A null node has height -1
        /// 
        /// [1]: http://books.google.com/books?id=NLngYyWFl_YC&lpg=PA296&vq=avl&pg=PA296#v=onepage&q&f=false
        /// [2]: http://en.wikipedia.org/wiki/Tree_(data_structure)#Terminology
        /// </summary>
        /// <param name="tree"></param>
        /// <param name="height"></param>
        /// <returns></returns>
        static bool IsBalanced(Node tree, out int height)
        {
            if (tree == null)
            {
                height = -1;
                return true;
            }

            if (!IsBalanced(tree.Left, out height))
            {
                return false;
            }

            int heightLeft = height;

            if (!IsBalanced(tree.Right, out height))
            {
                return false;
            }

            if (Math.Abs(height - heightLeft) > 1)
            {
                return false;
            }

            height = Math.Max(height, heightLeft) + 1;
            return true;
        }
Ejemplo n.º 2
0
        static void Main(string[] args)
        {
            int height;

            Node tree = null;
            Debug.Assert(IsBalanced(tree, out height) == true && height == -1);

            tree = new Node();
            Debug.Assert(IsBalanced(tree, out height) == true && height == 0);

            tree = new Node(
                left: new Node(),
                right: null);
            Debug.Assert(IsBalanced(tree, out height) == true && height == 1);

            tree = new Node(
                left: new Node(
                    left: new Node()),
                right: new Node(
                    right: new Node()));
            Debug.Assert(IsBalanced(tree, out height) == true && height == 2);

            tree = new Node(
                left: new Node(
                    left: new Node(
                        left: new Node())),
                right: new Node(
                    right: new Node(
                        right: new Node())));
            Debug.Assert(IsBalanced(tree, out height) == false); // don't need to check height

            Console.WriteLine("passed.");
            Console.Read();
        }
Ejemplo n.º 3
0
 public Node(Node left = null, Node right = null)
 {
     Left = left; Right = right;
 }