您的位置:首页 > 其它

Leetcode 最小二叉树深度和删除数组重复元素

2013-04-11 20:43 495 查看
Number114 最小二叉树深度

class Solution {
public:
int minDepth(TreeNode *root) {
int depth=0;
if(root==NULL)return 0;
int left=minDepth(root->left);
int right=minDepth(root->right);
if(root->left==NULL&&root->right!=NULL)
{
depth=right+1;
}
else if(root->right==NULL&&root->left!=NULL)
{
depth=left+1;
}
else if(root->left==NULL&&root->right==NULL)
depth=depth+1;
else
depth=left<right ? left+1 : right+1;
return depth;
}
};


Number 80 删除数组重复元素

class Solution {
public:
int removeDuplicates(int A[], int n) {
if(n==0)return 0;
int i,j;
int current=A[0];
int count=1;
for(i=1,j=1;i<n;i++)
{
if(A[i]==current)
{
count++;
if(count<=2)
A[j++]=current;
}
if(A[i]!=current)
{
current=A[i];
A[j++]=current;
count=1;
}
}
return j;
}
};


Number 100 same tree

/**
* Definition for binary tree
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isSameTree(TreeNode *p, TreeNode *q) {
if(p==NULL&&q==NULL)
return true;
if(p==NULL&&q!=NULL)return false;
if(p!=NULL&&q==NULL)return false;
if(p->val==q->val)
{
return isSameTree(p->left,q->left)&&isSameTree(p->right,q->right);
}
else return false;
}
};


Number 94 二叉树中序遍历

class Solution {
public:
vector<int> inorderTraversal(TreeNode *root) {
vector<int> v;
TreeNode *s[100];
int top=-1;
if(root==NULL)return v;
TreeNode *p=root;
//s[++top]=p;
while(p||top!=-1)
{
while(p)
{
s[++top]=p;
p=p->left;
}
if(top!=-1)
{
p=s[top];
v.push_back(p->val);
top--;
p=p->right;
}
}
return v;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐