二叉树的深度和平衡性

public class SBinaryTree
    {
        public int Value;
        public SBinaryTree LeftChild;
        public SBinaryTree RightChild;

        public SBinaryTree(int value, SBinaryTree left, SBinaryTree right)
        {
            Value = value;
            LeftChild = left;
            RightChild = right;
        }
    }
    //SBinaryTree m = new SBinaryTree(4, null, null);
    
//SBinaryTree a = new SBinaryTree(4, m, null);
    
//SBinaryTree b = new SBinaryTree(12, null, null);
    
//SBinaryTree c = new SBinaryTree(16, null, null);
    
//SBinaryTree d = new SBinaryTree(6, a, null);
    
//SBinaryTree e = new SBinaryTree(14, b, c); 
    
//SBinaryTree f = new SBinaryTree(10, d, e);
    public class BinaryTree
    {
        public int GetDepth(SBinaryTree root)
        {
            if (root == null)
                return 0;
            int leftDepth = 0;
            int rightLeft = 0;
            int bigDepth = 0;
            if (root.LeftChild != null)
            {
                leftDepth = GetDepth(root.LeftChild);
            }

            if (root.RightChild != null)
            {
                rightLeft = GetDepth(root.RightChild);
            }

            bigDepth = leftDepth > rightLeft ? leftDepth : rightLeft;

            return bigDepth + 1;
        }

        public bool IsBalanced(SBinaryTree tree, ref int depth)
        {
            if (tree == null)
            {
                depth = 0;
                return true;
            }

            int leftDepth = 0;
            int rightDepth = 0;

            if (IsBalanced(tree.LeftChild, ref leftDepth) && IsBalanced(tree.RightChild, ref rightDepth))
            {
                depth = leftDepth > rightDepth ? leftDepth + 1 : rightDepth + 1;

                if (Math.Abs(leftDepth - rightDepth) <= 1)
                    return true;
            }
            return false;
        }
    }
posted @ 2011-12-18 18:07  xpwilson  阅读(321)  评论(0编辑  收藏  举报