Leetcode0100--Same Tree 相同树

【转载请注明】http://www.cnblogs.com/igoslly/p/8707664.html

 

来看一下题目:

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

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

 

Example 1:

Input:     1         1

             / \       / \

           2   3     2   3

        [1,2,3],   [1,2,3]

 

Output: true

Example 2:

Input:     1         1

            /           \

         2             2

        [1,2],     [1,null,2]

 

Output: false

题目意思:

判断两个二叉树是否相等

 

注意点:

1、区分左结点和右结点

2、虽然题目给的数组形式,但代码中还是以ListNode* 结点给出

思路:

      1、分别遍历树1和树2,结束前若有结点不同,直接返回false

 


 

实现方法1:

    使用前序遍历方法进行遍历,dfs()子函数递归操作

void dfs(bool * flag,TreeNode *node1,TreeNode * node2){
    if(!(*flag)){return;}   // 判断结果false,无需后续操作,直接返回
    if(node1==NULL&&node2!=NULL){*flag=false;return;}
    if(node1!=NULL&&node2==NULL){*flag=false;return;}   // 若一方为NULL,一方还有值,直接判定false
    if(node1==NULL&&node2==NULL){return;}               // 两方均到根结点、遍历结束
    if(node1->val!=node2->val){*flag=false;return;}     // 当前根结点
    // 遍历左结点和右结点
    dfs(flag,node1->left,node2->left);    
    dfs(flag,node1->right,node2->right);
}
class Solution {
public:
    bool isSameTree(TreeNode* p, TreeNode* q) {
        bool flag=true;
        dfs(&flag,p,q);
        return flag;
        
    }
};

 实现方法2:

    简化写法,直接递归原函数isSameTree,首先:① 取消子函数dfs  ②  无需分别判断 node1 & node2 的NULL情况

class Solution {
public:
    bool isSameTree(TreeNode* p, TreeNode* q) {
        if (p&&q)   // p & q 均有值
            return(p->val==q->val && isSameTree(p->left,q->left) && isSameTree(p->right,q->right));
        // return 先判断当前值是否相等
        // 遍历左子树和右子树
        
        else if (p||q)    // p & q 不都有值
            return false;
        else              // p & q 都无值
            return true;
    }
};

扩展:

在某个大神的代码里看到如下几行,是来做为了优化C++流中不断刷新缓冲区,进行:

static int x = [](){ 
    std::ios::sync_with_stdio(false); 
    cin.tie(NULL);  
    return 0; 
}();

具体解释可以看链接:https://www.cnblogs.com/PrayG/p/5749832.html

 

转载于:https://www.cnblogs.com/igoslly/p/8707664.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值