How to determine if binary tree is balanced?

前端 未结 27 1512
萌比男神i
萌比男神i 2020-11-30 16:11

It\'s been a while from those school years. Got a job as IT specialist at a hospital. Trying to move to do some actual programming now. I\'m working on binary trees now, a

27条回答
  •  清歌不尽
    2020-11-30 17:02

    Here is a complete worked out tested solution in C# (sorry I'm no java dev) (just copy paste in console app). I know that definition of balanced varies so not everyone may like my test results but please just look at the slightly different approach of checking depth/height in a recursive loop and exiting on the first mismatch without saving node height/level/depth on each node (only maintaining it in a function call).

    using System;
    using System.Linq;
    using System.Text;
    
    namespace BalancedTree
    {
        class Program
        {
            public static void Main()
            {
                //Value Gathering
                Console.WriteLine(RunTreeTests(new[] { 0 }));
                Console.WriteLine(RunTreeTests(new int[] { }));
    
                Console.WriteLine(RunTreeTests(new[] { 0, 1, 2, 3, 4, -1, -4, -3, -2 }));
                Console.WriteLine(RunTreeTests(null));
                Console.WriteLine(RunTreeTests(new[] { 10, 8, 12, 8, 4, 14, 8, 10 }));
                Console.WriteLine(RunTreeTests(new int[] { 20, 10, 30, 5, 15, 25, 35, 3, 8, 12, 17, 22, 27, 32, 37 }));
    
                Console.ReadKey();
            }
    
            static string RunTreeTests(int[] scores)
            {
                if (scores == null || scores.Count() == 0)
                {
                    return null;
                }
    
                var tree = new BinarySearchTree();
    
                foreach (var score in scores)
                {
                    tree.InsertScore(score);
                }
    
                Console.WriteLine(tree.IsBalanced());
    
                var sb = tree.GetBreadthWardsTraversedNodes();
    
                return sb.ToString(0, sb.Length - 1);
            }
        }
    
        public class Node
        {
            public int Value { get; set; }
            public int Count { get; set; }
            public Node RightChild { get; set; }
            public Node LeftChild { get; set; }
            public Node(int value)
            {
                Value = value;
                Count = 1;
            }
    
            public override string ToString()
            {
                return Value + ":" + Count;
            }
    
            public bool IsLeafNode()
            {
                return LeftChild == null && RightChild == null;
            }
    
            public void AddValue(int value)
            {
                if (value == Value)
                {
                    Count++;
                }
                else
                {
                    if (value > Value)
                    {
                        if (RightChild == null)
                        {
                            RightChild = new Node(value);
                        }
                        else
                        {
                            RightChild.AddValue(value);
                        }
                    }
                    else
                    {
                        if (LeftChild == null)
                        {
                            LeftChild = new Node(value);
                        }
                        else
                        {
                            LeftChild.AddValue(value);
                        }
                    }
                }
            }
        }
    
        public class BinarySearchTree
        {
            public Node Root { get; set; }
    
            public void InsertScore(int score)
            {
                if (Root == null)
                {
                    Root = new Node(score);
                }
                else
                {
                    Root.AddValue(score);
                }
            }
    
            private static int _heightCheck;
            public bool IsBalanced()
            {
                _heightCheck = 0;
                var height = 0;
                if (Root == null) return true;
                var result = CheckHeight(Root, ref height);
                height--;
                return (result && height == 0);
            }
    
            private static bool CheckHeight(Node node, ref int height)
            {
                height++;
                if (node.LeftChild == null)
                {
                    if (node.RightChild != null) return false;
                    if (_heightCheck != 0) return _heightCheck == height;
                    _heightCheck = height;
                    return true;
                }
                if (node.RightChild == null)
                {
                    return false;
                }
    
                var leftCheck = CheckHeight(node.LeftChild, ref height);
                if (!leftCheck) return false;
                height--;
                var rightCheck = CheckHeight(node.RightChild, ref height);
                if (!rightCheck) return false;
                height--;
                return true;
            }
    
    
            public StringBuilder GetBreadthWardsTraversedNodes()
            {
                if (Root == null) return null;
                var traversQueue = new StringBuilder();
                traversQueue.Append(Root + ",");
                if (Root.IsLeafNode()) return traversQueue;
                TraversBreadthWards(traversQueue, Root);
                return traversQueue;
            }
    
            private static void TraversBreadthWards(StringBuilder sb, Node node)
            {
                if (node == null) return;
                sb.Append(node.LeftChild + ",");
                sb.Append(node.RightChild + ",");
                if (node.LeftChild != null && !node.LeftChild.IsLeafNode())
                {
                    TraversBreadthWards(sb, node.LeftChild);
                }
                if (node.RightChild != null && !node.RightChild.IsLeafNode())
                {
                    TraversBreadthWards(sb, node.RightChild);
                }
            }
        }
    }
    

提交回复
热议问题