每日一题--检验树是否平衡(Google推荐面试书--Cracking the Coding Interview)

题目

  • 原文:
    Implement a function to check if a tree is balanced. For the purposes of this question, a balanced tree is defined to be a tree such that no two leaf nodes differ in distance from the root by more than one.
  • 译文:
    设计一个函数检查一棵树是否平衡。在这个问题中的平衡树指的是这棵树任意两个叶子结点到根结点的距离之差不大于1。

分析
递归找叶节点的最大、最小深度,然后相减即可。
值得注意的是,在找最小深度时候和最大深度有所区分,因为当某个结点的子树是null的时候,它不一定是叶子节点。

代码

#include <iostream>
#include <cmath>
using namespace std; 

struct TreeNode {
	int value;
	TreeNode *leftchild, *rightchild;
};


TreeNode* createTreeNode(int val) {
	TreeNode *node = new TreeNode;
	node->value = val;
	node->leftchild = NULL;
	node->rightchild = NULL;
	
	return node;
}

void insert(TreeNode **tree,int val) {
	if(*tree == NULL) {
		cout << "createTreeNode:";
		*tree = createTreeNode(val);
		cout << (*tree)->value << endl;
		return;
	}
	else if((*tree)->value > val) {
		return insert(&(*tree)->leftchild, val);
	}
	else {
		return insert(&(*tree)->rightchild, val);
	}
}

int minDepth(TreeNode **tree) {
  if (*tree == NULL)
    return 0;
  if ((*tree)->leftchild == NULL && (*tree)->rightchild == NULL)
    return 1; //说明是个leaf了!
  int left = minDepth(&(*tree)->leftchild);
  int right = minDepth(&(*tree)->rightchild);
  return min(left, right) + 1;
}

int maxDepth(TreeNode **tree) {
  if (*tree == NULL)
    return 0;
  int left = maxDepth(&(*tree)->leftchild);
  int right = maxDepth(&(*tree)->rightchild);
  return max(left, right) + 1;
}

bool isBalanceTree(TreeNode **tree) {
	return (maxDepth(tree)-minDepth(tree)) <= 1;
}

void printTree(TreeNode **tree) {
	if(*tree != NULL) {
		cout << (*tree)->value << " ";
		printTree(&(*tree)->leftchild);
		printTree(&(*tree)->rightchild);
	}
}

void deleteTree(TreeNode **tree) {
	if(*tree != NULL) {
		deleteTree(&(*tree)->leftchild);
		deleteTree(&(*tree)->rightchild);
		delete *tree;
	}
}

int main() {
	TreeNode *treenode = NULL;
	TreeNode **tree = &treenode;
	int a[] = {
		5, 3, 8, 1, 4, 7, 10, 2, 6, 9, 11, 12
	};
	for(int i=0; i<12; ++i)
		insert(tree, a[i]);
	printTree(tree);
	
	cout << "max Depth is" << maxDepth(tree) << ",and min Depth is" << minDepth(tree) << endl;
	cout << "the tree is a balance tree?" << isBalanceTree(tree) << "(1--yes; 0--false)" << endl;
	
	deleteTree(tree);
}

结果
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_39860046/article/details/88031696