[LeetCode]--100. Same Tree

简介: Given two binary trees, write a function to check if they are equal or not.Two binary trees are considered equal if they are structurally identical and the nodes have the same value.pub

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

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

public boolean isSameTree(TreeNode p, TreeNode q) {
        if (p == null && q == null)
            return true;
        if ((p == null && q != null) || (p != null && q == null)) {
            System.out.println(2);
            return false;
        }

        if ((p.left != null && q.left == null)
                || (p.left == null && q.left != null)
                || (p.right == null && q.right != null)
                || (p.right != null && q.right == null)) {
            System.out.println(1);
            return false;
        }
        if (p.val != q.val)
            return false;
        return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
    }

通过了,但是我在想子树的判断对不对,其实中间那一段代码时可以不要的,因为递归循环到子树的时候(p == null && q != null) || (p != null && q == null)这个判断已经包含了左子树和右子树的判断。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public boolean isSameTree(TreeNode p, TreeNode q) {
        if (p == null && q == null)
            return true;
        if ((p == null && q != null) || (p != null && q == null))
            return false;
        if (p.val != q.val)
            return false;
        return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
    }
}

再推荐一种简单的写法,不过我觉得容易混淆。

public boolean isSameTree1(TreeNode p, TreeNode q) {
        return (p == null && q == null)
                || ((p != null && q != null && p.val == q.val) && (isSameTree1(
                        p.left, q.left) && isSameTree(p.right, q.right)));
    }
目录
相关文章
LeetCode 100. Same Tree
此题目是给定两棵树,判断两个树是否相等.
52 0
LeetCode 100. Same Tree
LeetCode 100 Same Tree(相同树判断)(二叉树、递归、栈和队列、深搜和宽搜)
版权声明:转载请联系本人,感谢配合!本站地址:http://blog.csdn.net/nomasp https://blog.csdn.net/NoMasp/article/details/50496422 翻译 给定两个二叉树,写一个函数检查他们是否相等。
773 0
【LeetCode从零单排】No100 Same Tree && No101 Symmetric Tree
题目 1.same tree Given two binary trees, write a function to check if they are equal or not. Two binary trees are considered equal if they are structurally identical and the nodes have the same value
873 0
|
16小时前
|
算法 C++
【刷题】Leetcode 1609.奇偶树
这道题是我目前做过最难的题,虽然没有一遍做出来,但是参考大佬的代码,慢慢啃的感觉的真的很好。刷题继续!!!!!!
8 0
|
16小时前
|
算法 索引
【刷题】滑动窗口精通 — Leetcode 30. 串联所有单词的子串 | Leetcode 76. 最小覆盖子串
经过这两道题目的书写,相信大家一定深刻认识到了滑动窗口的使用方法!!! 下面请大家继续刷题吧!!!
11 0

热门文章

最新文章