Maximum Depth of Binary Tree & Same Tree & Reverse Integer
来源:互联网 发布:非负矩阵分解算法综述 编辑:程序博客网 时间:2024/06/03 07:15
简单题三连发!!!
(1) Maximum Depth of Binary Tree
求树的最大深度,一个递归搞定:
class Solution {public: int maxDepth(TreeNode *root) { if(root==NULL) return 0; if(root->left==NULL && root->right==NULL) return 1; return 1+max(maxDepth(root->left),maxDepth(root->right)); }};网上有非递归的解法[1],用BFS搜索,利用了队列作为保存当前已遍历的节点。注意STL中queue的用法
(2) Same Tree
判断两个树是否一样,同样用递归:
class Solution {public: bool isSameTree(TreeNode *p, TreeNode *q) { if(p==NULL&& q==NULL) return true; if(p==NULL&& q!=NULL || q==NULL&&p!=NULL || p->val!=q->val) return false; if(p->val==q->val) return(isSameTree(p->left,q->left) & isSameTree(p->right,q->right)); }};[2]也有种非递归解法,也是用BFS搜索和队列。
(3) Reverse Integer
倒写整数,非常简单:
class Solution {public: int reverse(int x) { int flag=x>0 ? 1 : -1 ,result=0; if(x<0) x=abs(x); while(x){ result=result*10+x%10; x=x/10; } return flag*result; }};
注意flag的用法很巧妙!
参考:
[1] http://blog.csdn.net/sunbaigui/article/details/8980887
[2] http://blog.csdn.net/sunbaigui/article/details/8981275
0 0
- Maximum Depth of Binary Tree & Same Tree & Reverse Integer
- 【LeetCode】Maximum Depth of Binary Tree&&Same Tree
- 【100】Same Tree && 【104】Maximum Depth of Binary Tree
- 104. Maximum Depth of Binary Tree&&100. Same Tree
- Maximum Depth of Binary Tree
- Maximum Depth of Binary Tree
- Maximum Depth of Binary Tree
- Maximum Depth of Binary Tree
- Maximum Depth of Binary Tree
- Maximum Depth of Binary Tree
- Maximum Depth of Binary Tree
- Maximum Depth of Binary Tree
- Maximum Depth of Binary Tree
- Maximum Depth of Binary Tree
- Maximum Depth of Binary Tree
- Maximum Depth of Binary Tree
- Maximum Depth of Binary Tree
- Maximum Depth of Binary Tree
- Hadoop生态圈开源项目总结
- Linux内核中的current_thread_info
- 第五周作业——有向图邻接表表示及反向图构造
- C++11 转移语义
- iOS多线程中的dispatch_semaphore_t semaphore(dispatch组和信号量。)
- Maximum Depth of Binary Tree & Same Tree & Reverse Integer
- Android UI控件详解-GridView(网格视图)
- 二维数组与指针
- Ruby学习笔记_Ruby的全局变量
- 我的第一个spring学习——用myeclipse开发spring
- math.h
- 友元函数
- lua的一个在线教程链接。。。
- 如何修改sqlserver2005的sa密码