判断平衡二叉树/二叉树镜像/一个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; }
相关文章推荐
- 判断二叉树平衡/求二叉树的镜像 附属: 一个m*n的矩阵,从左到右从上到下都是递增的,给一个数x,判断x是否在矩阵中
- 矩阵找数--一个m*n的矩阵,从左到右从上到下都是递增的,给一个数x,判断x是否在矩阵中。要求效率尽可能的高。
- 一个m*n的矩阵,从左到右从上到下都是递增的,给一个数x,判断x是否在矩阵中。要求效率尽可能的高
- 一个m*n的矩阵,从左到右从上到下都是递增的,给一个数x,判断x是否在矩阵中。要求效率尽可能的高
- 一个m*n的矩阵,从左到右从上到下都是递增的,给一个数x,判断x是否在矩阵中。要求效率尽可能的高。
- 一个m*n的矩阵,从左到右从上到下都是递增的,给一个数x,判断x是否在矩阵中。要求效率尽可能的高。
- 一个m*n的矩阵,从左到右从上到下都是递增的,给一个数x,判断x是否在矩阵中。(高效率)
- 一个m*n的矩阵,从左到右从上到下都是递增的,给一个数x,判断x是否在矩阵中。
- 一个m*n的矩阵,从左到右从上到下都是递增的,给一个数x,判断x是否在矩阵中
- 【c语言】二维数组中的查找,杨氏矩阵在一个二维数组中,每行都按照从左到右的递增的顺序排序,输入这样的一个数组和一个数,判断数组中是否包含这个数
- (Array) 一个 N*N 的矩阵,每一行从左到右有序,每一列从上到下有序,都是递增,写个程序,判断一个数是否在矩阵中。
- 在一个从左到右从上到下都是递增的m*n的矩阵中找一个数x
- 请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。
- 在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数
- matlab判断一个矩阵中的元素是否完全一致
- PHP实现在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
- 程序员面试题目总结--数组(一)【递归求数组所有元素和、用一个for循环打印出一个二维数组、用递归判断数组是否是递增、有序数组中删除重复元素】
- 在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
- 在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。 请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数
- 【树】判断二叉树是否镜像 + 将一个二叉树变成其镜像