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
原创粉丝点击