Maximum Depth of Binary Tree & Same Tree & Reverse Integer

简单题三连发!!!

(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




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值