树的判断:二叉搜索树,平衡二叉树

这两个判断里都埋有坑
二叉树搜索树:不能用递归的方式直接判断
                       这里用中序遍历,判断遍历的节点是否是递增的,用prev保存上一个遍历的节点
                       当前节点的值一定小于prev的值
bool  IsBST(TreeNode* pRoot)
	{
		static TreeNode *prev = NULL;

		if (pRoot)
		{
			if (!IsBST(pRoot->left))
				return false;
			if (prev != NULL&&pRoot->val <= prev->val)
				return false;
			prev = pRoot;

			return IsBST(pRoot->right);			
		}
		return true;

	}

平衡二叉树:跟二叉树的深度有关
求深度

int TreeDepth(TreeNode* pRoot)
	{
		if (pRoot == NULL)
			return 0;
		
		return 1 + max(TreeDepth(pRoot->left), TreeDepth(pRoot->right));
	}

我们现在要在求深度的同时,后序的判断左右子树的高度相差是否小于等于1
下面是两个求深度的比较

	bool res = true;


	int TreeDepth(TreeNode* root)
	{
		if (root == NULL)
			return 0;
		int left = TreeDepth(root->left);
		int right = TreeDepth(root->right);	
		return max(left, right) + 1;
	}


	int TreeDepth1(TreeNode* root)
	{
		if (root == NULL)
			return 0;
		int left = TreeDepth1(root->left);
		int right = TreeDepth1(root->right);
		if (abs(left - right) > 1)
			res = false;
		return max(left, right) + 1;
	}
平衡二叉树的函数就可以返回res的值

猜你喜欢

转载自blog.csdn.net/eereere/article/details/80347290