zoukankan      html  css  js  c++  java
  • (015)实现一个函数来检查是否平衡树(keep it up)

    实现一个函数来检查是否平衡树。这个问题而言。 平衡指的是这棵树随意两个叶子结点到根结点的距离之差不大于1。

    这个题我们能够採用暴力搜索,找到叶子节点到根节点的最小值和最大值。然后他们的差假设大于1就不是平衡树,反之

    则是平衡树。

    int MinDepth = std::numeric_limits<int>::max();
    int MaxDepth = std::numeric_limits<int>::min();
    
    struct TreeNode
    {
    	int data;
    	TreeNode* child;
    	TreeNode* brother;
    };
    
    bool isBlanceTree(const TreeNode* vNode, int vDepth=0)
    {
    	if (vNode == NULL)
    	{
    		if (vDepth == 0) return true;
    
    		if (vDepth < MinDepth) 
    		{
    			MinDepth = vDepth;
    		}
    
    		if (vDepth > MaxDepth)
    		{
    			MaxDepth = vDepth;
    		}
    
    		if (MaxDepth - MinDepth > 1) return false;
    		return true;
    	}
    
    	bool IsBlance = true;
    	if (vNode->child != NULL)
    	{
    		IsBlance = isBlanceTree(vNode->child, vDepth+1);
    	}
    
    	if (IsBlance && vNode->brother != NULL)
    	{
    		IsBlance = isBlanceTree(vNode->brother, vDepth);
    	}
    
    	return IsBlance;
    }


    版权声明:本文博客原创文章,博客,未经同意,不得转载。

  • 相关阅读:
    强迫症患者
    GG的匹配串
    漂洋过海来看你
    Fire or Retreat
    1011. A+B和C (15)
    1010. 一元多项式求导 (25)
    1009. 说反话 (20)
    1008. 数组元素循环右移问题 (20)
    1007. 素数对猜想 (20)
    1006. 换个格式输出整数 (15)
  • 原文地址:https://www.cnblogs.com/gcczhongduan/p/4676470.html
Copyright © 2011-2022 走看看