您的位置:首页 > 其它

判断平衡二叉树/二叉树镜像/一个m*n的矩阵,从左到右从上到下都是递增的,给一个数x,判断x是否在矩阵中

2017-07-25 18:42 471 查看

判断一棵二叉树是否是平衡二叉树

方法一:

class Solution {
public:
/**
* @param root: The root of binary tree.
* @return: True if this Binary tree is Balanced, or false.
*/
int depth(TreeNode* root)
{
if(root==NULL)
return 0;

int left=depth(root->left);
int right=depth(root->right);
return left>right?(left+1):(right+1);
}
bool isBalanced(TreeNode *root) {
// write your code here
if(root==NULL)
return true;

int left=depth(root->left);
int right=depth(root->right);
int tmp=abs(left-right);
if(tmp>1)
return false;

return isBalanced(root->left)&&isBalanced(root->right);
}
};


方法二:

class Solution {
public:
/**
* @param root: The root of binary tree.
* @return: True if this Binary tree is Balanced, or false.
*/
bool isBalanced(TreeNode* root,int* depth)
{
if(root==NULL)
{
*depth=0;
return true;
}
int leftdepth,rightdepth;
bool left=isBalanced(root->left,&leftdepth);
bool right=isBalanced(root->right,&rightdepth);
if(left&&right)
{
int tmp=abs(leftdepth-rightdepth);
if(tmp<=1)
{
*depth=(leftdepth>rightdepth?leftdepth:rightdepth)+1;
return true;
}

}
return false;
}
bool isBalanced(TreeNode* root)
{
int depth=0;
return isBalanced(root,&depth);
}
};


求一颗二叉树的镜像

class Solution {
public:
/**
* @param root: a TreeNode, the root of the binary tree
* @return: nothing
*/
void invertBinaryTree(TreeNode *root) {
// write your code here
if(root==NULL)
return;
invertBinaryTree(root->left);
invertBinaryTree(root->right);
swap(root->left,root->right);
}
};


一个m*n的矩阵,从左到右从上到下都是递增的,给一个数x,判断x是否在矩阵中

要求:效率尽可能的高

bool isin(vector<vector<int>>& v,int x)
{
int m = v.size();
int n = v[0].size();
int j = n-1;
int i = 0;
while (i<m&&j>=0)
{
if (x == v[i][j])
return true;
else if (x>v[i][j])
{
i++;
}
else//x<
{
j--;
}
}
return false;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐