剑指offer面试题之判断一颗二叉树是不是平衡二叉树
2016-03-18 14:32
501 查看
1,题目:
输入一棵二叉树,判断该二叉树是否是平衡二叉树。
2,思想:
考虑树为空的情况;
(1)算左右子树的深度,再相减,若等于-1,1和0即为平衡二叉树,若不是则为否。
则问题就转化为了求一颗树的深度了。
在牛客网上的编码为:
输入一棵二叉树,判断该二叉树是否是平衡二叉树。
2,思想:
考虑树为空的情况;
(1)算左右子树的深度,再相减,若等于-1,1和0即为平衡二叉树,若不是则为否。
则问题就转化为了求一颗树的深度了。
在牛客网上的编码为:
class Solution { public: int depthofnode(TreeNode* p){ if (p == NULL) { return 0; } queue<TreeNode*> q; q.push(p); int level = 0; int length = 0; while (!q.empty()) { level++; length = q.size(); while (length--) { TreeNode* temp = q.front(); q.pop(); if (temp->left) { q.push(temp->left); } if (temp->right) { q.push(temp->right); } } } return level; } bool IsBalanced_Solution(TreeNode* pRoot) { if (pRoot == NULL) { return true; } int leftdepth = depthofnode(pRoot->left); int rightdepth = depthofnode(pRoot->right); int balance = leftdepth - rightdepth; if (balance == 0) { return true; } else if (balance == -1) { return true; } else if (balance == 1) { return true; } else return false; } };
相关文章推荐