平衡二叉树是指:父节点的左子树和右子树的高度之差不能大于1,也就是说不能高过1层。
判断一棵树是否为平衡二叉树,需要判断每个节点的左右子树的深度,只判断整个树的根节点是不行的。
刚做了一道求树的深度的题,然后这道题想当然就去先求根节点的左右子树的深度差是否大于1,然后分别求根节点的左子树和右子树进行递归。这样一来,树的节点会被遍历好多遍,时间复杂度较高。
答案是这样写的:对树进行后序遍历,同时伴随着每个节点的左右字数的深度值,只要有某一个节点的左右子树深度差大于1,就将flag标志位置false。
#include <iostream> #include <vector> #include <algorithm> using namespace std; struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) { } }; //int TreeDepth(TreeNode* pRoot) //{ // if (!pRoot) // return 0; // int left = TreeDepth(pRoot->left); // int right = TreeDepth(pRoot->right); // if (left >= right) // return left + 1; // else { // return right + 1; // } //} bool flag = true; int getDepth(TreeNode* pRoot) { if (pRoot == NULL) { return 0; } int left = getDepth(pRoot->left); int right = getDepth(pRoot->right); if (abs(left - right) > 1) flag = false; return left > right ? left + 1 : right + 1; } bool IsBalanced_Solution(TreeNode* pRoot) { int re = getDepth(pRoot); return flag; } int main() { TreeNode* t = new TreeNode(1); t->left = new TreeNode(2); t->right = new TreeNode(3); t->right->left = new TreeNode(4); t->right->left->right = new TreeNode(5); bool b = IsBalanced_Solution(t); cout << b << endl; return 0; }
代码中注释了的是一段求子树的深度值的程序。