您的位置:首页 > 其它

【LeetCode】三道简单的递归问题

2016-06-19 08:52 369 查看
1.single-number

Given an array of integers, every element appears twice except for one. Find that single one.

Note:

Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

class Solution {
public:
int singleNumber(int A[], int n) {
int rs = 0;

for (int i = 0; i < n; i++)
{
rs ^= A[i];
}
return rs;
}
};


2.maximum-depth-of-binary-tree

Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

/**
* Definition for binary tree
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int maxDepth(TreeNode *root) {

if (NULL == root)
return 0;
int l = maxDepth(root->left);
int r = maxDepth(root->right);
return l > r ? l + 1 : r + 1;
}
};


3.same-tree

Given two binary trees, write a function to check if they are equal or not.

Two binary trees are considered equal if they are structurally identical and the nodes have the same value.

/**
* 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 (NULL == p && NULL == q)
return true;
if (NULL == p || NULL == q)
return false;
if (p->val == q->val)
{
bool rs1, rs2;
rs1 = isSameTree(p->left, q->left);
rs2 = isSameTree(p->right, q->right);
if (rs1 && rs2)
return true;
}
return false;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: