LeetCode_Simple_100. Same Tree

2019.1.20

题目描述:

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

Example 3:

Input:     1         1
          / \       / \
         2   1     1   2

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

Output: false

这题是比较两棵二叉树是否是相同的二叉树,相同的树的定义是:两棵二叉树结构相同,并且对应结点的值也相同,那么这两棵树就是相同的树。

总所周知,二叉树是典型的递归结构,所以很多二叉树的问题都可以用递归来解决,这题就可以用递归来解决。

解法一:

1.若两棵树一棵是空树一棵不是空树,则返回false;

2.若两棵树都是空树,则返回true;

3.若两棵树都不是空树,但是对应的结点的值不同,则返回false;

4.若两棵树都不是空树,且对应的结点的值相同,则递归比较两棵树的左子树与右子树,返回两者的与作为结果返回。

PS.实际上就是对二叉树进行DFS递归。

C++代码:

/**
 * Definition for a binary tree node.
 * 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(!p&&q||p&&!q)
            return false;
        else if(!p&&!q)
            return true;
        else if(p->val!=q->val)
            return false;
        else 
            return isSameTree(p->left,q->left)&&isSameTree(p->right,q->right);
    }
};

执行时间:0ms;

PS.提交完看讨论,说执行时间主要取决于网速和环境,没什么参考价值,所以以后就不贴执行时间了。

解法二:

当然也可以将递归转换为迭代来做,有兴趣的同学可以查阅二叉树先序,中序,后序和层序的递归与非递归的转换的相关资料自己学习一下,主要就是要用到栈,这里就不赘述了。

C++代码:

class Solution {
    public boolean isSameTree(TreeNode p, TreeNode q) {
        if (p == null && q != null) {
            return false;
        }
        Stack<TreeNode> stack1 = new Stack<>();
        Stack<TreeNode> stack2 = new Stack<>();
        TreeNode cur1 = p;
        TreeNode cur2 = q;
        while (cur1 != null || !stack1.isEmpty()) {
            if (cur1 != null) {
                if (cur2 == null || cur1.val != cur2.val) {
                    return false;
                }
                stack1.push(cur1);
                cur1 = cur1.left;
                stack2.push(cur2);
                cur2 = cur2.left;
            } else {
                if (cur2 != null) {
                    return false;
                }
                cur1 = stack1.pop();
                cur1 = cur1.right;
                cur2 = stack2.pop();
                cur2 = cur2.right;
            }
        }
        return true;
    }
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值