示例#1
0
        public int IsBalanced(BST root)
        {
            int leftNodeHeight = 0;
            int righNodeHeight = 0;

            if (root == null)
            {
                return(0);
            }

            if (root.left != null)
            {
                leftNodeHeight = IsBalanced(root.left);
            }
            if (leftNodeHeight == -1)
            {
                return(-1);
            }

            if (root.right != null)
            {
                righNodeHeight = IsBalanced(root.right);
            }
            if (righNodeHeight == -1)
            {
                return(-1);
            }

            if (Math.Abs(leftNodeHeight - righNodeHeight) > 1)
            {
                return(-1);
            }

            // return Math.Abs(leftNodeHeight-righNodeHeight) <= 1 ? 1 : 0;
            return(Math.Max(leftNodeHeight, righNodeHeight) + 1);
        }
示例#2
0
 public BST(int data)
 {
     this.data = data;
     this.left = this.right = null;
 }