【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?
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.
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.
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; } };
相关文章推荐
- Cocos2d-x之helloworld
- Arduino 卡片5炫彩LED
- 附加作业
- jquery easyui 插件开发
- ASP.NET应用程序和页面生命周期
- Windows存储管理之磁盘类型简介
- Windows存储管理之磁盘类型简介
- 常用命令记录
- git 基本命令
- AppStore上传苹果应用程序软件发布流程
- 大型互联网技术架构1-架构概述
- ViewState与UpdatePanel探秘
- jBPM4.4 maven-dependencies
- 自定义控件之重写ScrollView实现图片下拉放大
- 进程的守护进程的用法
- 放假寂寞,敲敲代码,写了下几个常见的排序算法
- 【LeetCode】sum-root-to-leaf-numbers
- iOS网络访问之使用AFNetworking
- UUID(通用唯一标识符)
- hdu 4886(hash + dfs)