leetcode-pp / 91alg-5-daily-check

91 天学算法第五期打卡
55 stars 14 forks source link

【Day 14 】2021-09-23 - 100. 相同的树 #29

Open azl397985856 opened 3 years ago

azl397985856 commented 3 years ago

100. 相同的树

入选理由

暂无

题目地址

https://leetcode-cn.com/problems/same-tree/

前置知识

如果两个树在结构上相同,并且节点具有相同的值,则认为它们是相同的。

示例 1:

输入: 1 1 / \ / \ 2 3 2 3

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

输出: true 示例 2:

输入: 1 1 / \ 2 2

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

输出: false 示例 3:

输入: 1 1 / \ / \ 2 1 1 2

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

输出: false

ghost commented 3 years ago

题目

  1. Same Tree

思路

DFS

代码

class Solution:
    def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
        if not p and not q:
            return True
        elif not p or not q or p.val!=q.val: 
            return False

        return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)

复杂度

Space: O(N) Time: O(N)

YuanWenLai commented 3 years ago

思路

1、DFS,递归树 2、DFS的判断下,看两个树的结点是否一致

代码

/**
 * @param {TreeNode} p
 * @param {TreeNode} q
 * @return {boolean}
 */
var isSameTree = function (p, q) {
  if (p == null && q == null) return true;
  else if (p == null || q == null) return false;
  else if (p.val != q.val) return false;
  else return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
};

复杂度分析

BlueRui commented 3 years ago

Problem Same Tree

Algorithm

Complexity

Code

Language: Java

public boolean isSameTree(TreeNode p, TreeNode q) {
    if (p == null && q == null) {
        return true;
    }
    if (p == null || q == null || p.val != q.val) {
        return false;
    }
    return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}
ruohai0925 commented 3 years ago

题目地址()

题目描述

前置知识

公司

思路

关键点

代码

Python3 Code:


# DFS, 主要是学习一下判断语句的简化写法,如下
class Solution:
    def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
        if not p and not q:
            return True
        elif not p or not q:
            return False
        elif p.val != q.val:
            return False
        else:
            return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)

复杂度分析

令 m 和 n 分别是两个二叉树的节点数。

xieyj17 commented 3 years ago
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
        if (p is None) and (q is None):
            return True
        if (p and not q) or (q and not p):
            return False   
        return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right) and (p.val == q.val)

使用DFS Space: O(N)

Time: O(N)

JinMing-Gu commented 3 years ago
class Solution {
public:
    bool isSameTree(TreeNode* p, TreeNode* q) {
        if (p == nullptr && q == nullptr) {
            return true;
        } else if (p == nullptr || q == nullptr) {
            return false;
        } else if (p->val != q->val) {
            return false;
        } else {
            return isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
        }
    }
};
ychen8777 commented 3 years ago

思路

检查当前node是否一致 (一致为空,或者val一样), 再递归检查左右子树

代码

class Solution {
    public boolean isSameTree(TreeNode p, TreeNode q) {

        if (p == null && q == null) {
            return true;
        }

        if (p == null || q == null) {
            return false;
        }

        // now neither p or q is null
        if (p.val != q.val) {
            return false;
        }

        return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);

    }
}

复杂度

时间: O(n) \ 空间: O(n)

xiezhengyun commented 3 years ago

思路

dfs,要判断树的结构以及相同结构的值

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} p
 * @param {TreeNode} q
 * @return {boolean}
 */
var isSameTree = function (p, q) {
  if (!p && !q) return true
  if (p == null || q == null) return false
  if (p.val !== q.val) return false

  var left = isSameTree(p.left, q.left)
  var right = isSameTree(p.right, q.right)
  return left && right
};

复杂度

两棵树的元素个数分别为 M,N,高度分别为 H1,H2

liuyangqiQAQ commented 3 years ago

递归一次遍历左右两边的节点即可

class Solution {
    public boolean isSameTree(TreeNode p, TreeNode q) {
        return isEq(p, q);
    }

    public boolean isEq(TreeNode node1, TreeNode node2) {
        if (node1 == node2) {
            return true;
        }
        if (node1 != null && node2 != null) {
            return node1.val == node2.val && isEq(node1.left, node2.left) && isEq(node1.right, node2.right);
        } else {
            return false;
        }
    }
}

时间复杂度: O(n) n为节点数量。遍历整个节点比较

空间复杂度:O(M) M为最短的一棵树的高度

Daniel-Zheng commented 3 years ago

思路

DFS。

代码(C++)

class Solution {
public:
    bool isSameTree(TreeNode* p, TreeNode* q) {
        if (p == nullptr && q == nullptr) {
            return true;
        } else if (p == nullptr || q == nullptr) {
            return false;
        } else if (p->val != q->val) {
            return false;
        } else {
            return isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
        }
    }
};

复杂度分析

AgathaWang commented 3 years ago
class Solution(object):
    def isSameTree(self, p, q):
        """
        :type p: TreeNode
        :type q: TreeNode
        :rtype: bool
        """
        # recursion
        # time complexity: O(N)
        if not p and not q:
            return True
        if not p or not q:
            return False
        else:
            return p.val==q.val and self.isSameTree(p.left,q.left) and self.isSameTree(p.right,q.right)
yan0327 commented 3 years ago

DFS深度遍历,并且同时遍历两个节点。若两个节点有一个=nil,则两个节点判断是否都为nil,是则返回true,否则返回false

func isSameTree(p *TreeNode, q *TreeNode) bool {
    if p == nil || q == nil{
        return p == nil && q == nil
    }
    if p.Val != q.Val {
        return false
    }
    return isSameTree(p.Left, q.Left)&& isSameTree(p.Right, q.Right)
}

时间复杂度O(n) 空间复杂度O(n)

skinnyh commented 3 years ago

Note

  1. Use recursion, compare root of p, q then compare the p.left with q.left and p.right with q.right.
  2. Use BFS to compare each layer. Compare each node from p and q's layer queue.
  3. Get the preorder and inorder traversal results of the two trees. Since preorder + inorder can determine a tree's structure, if the two lists of two trees are the same then they are the same tree.

Solution

class Solution:
    def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
        if not p or not q:
            return p == q
        return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)

Time complexity: O(N)

Space complexity: O(H)

chenming-cao commented 3 years ago

解题思路

递归,递归出口为高度为1的树,每个节点分别判断两个左子树是否相等,两个右子树是否分别相等。

代码

class Solution {
    public boolean isSameTree(TreeNode p, TreeNode q) {
        if (p == null && q == null) return true;
        if (p == null || q == null) return false;
        if (p.val != q.val) return false;
        return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
    }
}

复杂度分析

AnhTom2000 commented 3 years ago

思路

两棵树同时采用中序遍历来判断是否是相同的树

代码:Java

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);
  }
}

复杂度分析

时间复杂度:O(min(p,q))

空间复杂度:O(min(ph,qh))

Cartie-ZhouMo commented 3 years ago

思路

递归。相同的树=节点值相同+左子树+右子树均是相同的树。

代码

class Solution:
    def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
        if not p and not q: return True
        if not p or not q: return False
        return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)

复杂度

chun1hao commented 3 years ago
var isSameTree = function (p, q) {
  if (!p && !q) return true;
  if (!p || !q) return false;
  if (p.val !== q.val) return false;
  return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
};

时间:O(N) 空间:O(N)

kendj-staff commented 3 years ago
class Solution {
    public boolean isSameTree(TreeNode p, TreeNode q) {
        return isSame(p,q);
    }
    public boolean isSame(TreeNode p, TreeNode q) {
        if (p == null && q == null) {
            return true;
        } else if (p == null || q == null) {
            return false;
        }

        return (p.val == q.val) && isSame(p.left, q.left) && isSame(p.right, q.right);
    }
}
flame0409 commented 3 years ago

思路:递归的进入左右子节点进行遍历

如果值不相同,返回false

如果一个节点不存在,返回false

class Solution {
    public boolean isSameTree(TreeNode p, TreeNode q) {
        if(p == null && q == null)return true;
        if(p == null || q == null)return false;
        if(p.val != q.val)return false;
        return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
    }
}

复杂度:

时间:O(min(m,n))

空间:O(min(m,n))

TimmmYang commented 3 years ago

思路

问题拆解成判断两个树是否相等只需要判断他们的左右子树是否相等,这样使用dfs遍历即可。

代码

class Solution:
    def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
        if p == None and q == None:
            return True
        if p == None or q == None:
            return False
        if p.val != q.val:
            return False
        return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)

复杂度

时间:O(N) N为两个树节点较小的一个。 空间:O(H) H为树的深度。

JinhMa commented 3 years ago

class Solution { public boolean isSameTree(TreeNode p, TreeNode q) { if (p == null && q == null) { return true; } else if (p == null || q == null) { return false; } else if (p.val != q.val) { return false; } else { return isSameTree(p.left, q.left) && isSameTree(p.right, q.right); } } }

MoncozGC commented 3 years ago
class Solution {
    public boolean isSameTree(TreeNode p, TreeNode q) {
        if (p == null || q == null) return p == q;
        return p.val == q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
    }
}
shamworld commented 3 years ago

思路

验证树的结构是是否相同,递归判断他们左右节点是否相同

代码

var isSameTree = function(p, q) {
    if(p==null&&q==null) return true;
    if(p==null||q==null) return false;

    return p.val==q.val&&isSameTree(p.left,q.left)&&isSameTree(p.right,q.right);
};

复杂度分析

Yufanzh commented 3 years ago

Intuition

Another DFS problem. Can be solved using recursive/iterative way.

Algorithm in Python3

class Solution:   
    def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
                #DFS recursive way
#             if p and q:
#                 return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)

#             if p == None and q == None:
#                 return True
#             else:
#                 return False

        # iterative method using stack
        # put p/q as a pair in stack to compare
        stack =[(p,q)]
        while len(stack) != 0:
            node1, node2 = stack.pop(0)
            if node1 and node2 and node1.val == node2.val:
                stack.append((node1.left, node2.left))
                stack.append((node1.right, node2.right))
            else:
                if node1 != node2:
                    return False
        return True

Complexity Analysis:

Joyce94 commented 3 years ago
思路

递归三要素 1、递归出口:最简单的情况,树高为1 2、分解子问题:求左子树、右子树情况 3、父问题与子问题的交集

代码
class Solution:
    def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
        if p is None and q is None:
            return True
        if p is None or q is None:
            return False
        if p.val != q.val:
            return False
        return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
复杂度

时间复杂度:o(n),n为节点个数 空间复杂度:o(h),h为树高度

iambigchen commented 3 years ago

思路

递归判断每一个节点是否相同

代码

var isSameTree = function(p, q) {
    if (p == null && q == null) {
        return true
    } else if (p == null || q == null) {
        return false
    }
    return p.val == q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right)
};

复杂度

时间复杂度 O(n) 空间复杂度 O(h) h为树的高度

user1689 commented 3 years ago

题目

https://leetcode-cn.com/problems/same-tree/

思路

DFS, BFS

python

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
        # 写法一
        def dfs(root1, root2):
            if not root1 and not root2:
                return True
            if root1 and not root2:
                return False
            if not root1 and root2:
                return False
            if root1.val != root2.val:
                return False

            return dfs(root1.left, root2.left) and dfs(root1.right, root2.right)

        return dfs(p, q)

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
        # 写法二
        if not p and not q: 
            return True
        elif not p or not q:
            return False
        elif p.val != q.val:
            return False
        else:
            queue1 = deque()
            queue2 = deque()
            queue1.append(p)
            queue2.append(q)
            while queue1 and queue2:
                node1 = queue1.popleft()
                node2 = queue2.popleft()
                if node1.val != node2.val:
                    return False

                left_node1, right_node1 = node1.left, node1.right
                left_node2, right_node2 = node2.left, node2.right

                 # 如果用或,两个都为空时,条件还是成立,回返回false
                 # 但是两个为空是相同结构,用异或是判断两边是否不相等,不相等就表示有一个不为空,会返回false.
                if (not left_node1) ^ (not left_node2):
                    return False

                if (not right_node1) ^ (not right_node2):
                    return False

                if node1.left:
                    queue1.append(node1.left)
                if node1.right:
                    queue1.append(node1.right)
                if node2.left:
                    queue2.append(node2.left)
                if node2.right:
                    queue2.append(node2.right)
        return True

复杂度分析

相关题目

  1. 待补充
doveshnnqkl commented 3 years ago

思路

BFS 每次将一层节点放入list,依次比较每个值

代码

java

class Solution {
    public boolean isSameTree(TreeNode p, TreeNode q) {
           LinkedList<TreeNode> list1 = new LinkedList<>();
           LinkedList<TreeNode> list2 = new LinkedList<>();
           list1.add(p);
           list2.add(q);
           while(list1.size() > 0){
               TreeNode tempP = list1.removeLast();
               TreeNode tempQ = list2.removeLast(); 
               if(tempP == null && tempQ != null){
                   return false;
               }
               if(tempP != null && tempQ == null){
                   return false;
               }
               if(tempP !=null && tempQ !=null){
                  if(tempP.val != tempQ.val){
                        return false;
                  }
                 list1.add(tempP.left);
                 list2.add(tempQ.left);
                 list1.add(tempP.right);
                 list2.add(tempQ.right);
               }           
           }
           return true;       
    }
}

复杂度

时间复杂度:O(min(m,n)),其中 m 和 n 分别是两个二叉树的节点数。

空间复杂度:O(min(m,n)),其中 mm 和 nn 分别是两个二叉树的节点数。空间复杂度取决于队列中的元素个数。

xbhog commented 3 years ago

100. 相同的树

思路:

根据题目给定的需求:

  1. 两节点都为null
  2. 两节点其中一个为null
  3. 节点值不相同

循环递归比较左左,右右。

Java代码段:

class Solution {
    public boolean isSameTree(TreeNode p, TreeNode q) {
        if(p == null && q == null) return true;
        if(p == null || q == null) return false;
        if(p.val != q.val) return false;
        return isSameTree(p.left,q.left) && isSameTree(p.right,q.right);
    }
}

复杂度分析:

时间复杂度:O(m) n:访问的最少节点数

空间复杂度:O(n) 最坏是数的高度

ginnydyy commented 3 years ago

Problem

https://leetcode.com/problems/same-tree/

Notes:

Solution:

Complexity

joeytor commented 3 years ago

思路

如果两个子树都是空子树, 那么就返回True, 因为相同

如果一个子树为空另一个不是空, 那么返回False

如果都不为空, 那么返回 这两个node value 相同 和, 左右子树 也相同, 如果都满足那么返回 True, 否则返回 False

代码

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
        if not p and not q:
            return True
        elif not p or not q:
            return False

        return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)

复杂度

时间复杂度: O(N) 遍历每一棵子树的每个节点

空间复杂度: O(N) 空间复杂度取决于递归栈的深度, 最差退化成链表, 所以是 O(N)

zszs97 commented 3 years ago

开始刷题

题目简介

【Day 14 】2021-09-23 - (100. 相同的树)

思路

题目代码

class Solution {
public:
    bool isSameTree(TreeNode* p, TreeNode* q) {
        if (p == nullptr && q == nullptr) {
            return true;
        } else if (p == nullptr || q == nullptr) {
            return false;
        } else if (p->val != q->val) {
            return false;
        } else {
            return isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
        }
    }
};

复杂度

Moin-Jer commented 3 years ago

思路


递归判断相同位置的值是否相等

代码


class Solution {
    public boolean isSameTree(TreeNode p, TreeNode q) {
        if (p == null && q == null) {
            return true;
        }
        if (p == null || q == null) {
            return false;
        }
        return p.val == q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
    }
}

复杂度分析


wangzehan123 commented 3 years ago

题目地址(100. 相同的树)

https://leetcode-cn.com/problems/same-tree/

题目描述

给你两棵二叉树的根节点 p 和 q ,编写一个函数来检验这两棵树是否相同。

如果两个树在结构上相同,并且节点具有相同的值,则认为它们是相同的。

 

示例 1:

输入:p = [1,2,3], q = [1,2,3]
输出:true

示例 2:

输入:p = [1,2], q = [1,null,2]
输出:false

示例 3:

输入:p = [1,2,1], q = [1,1,2]
输出:false

 

提示:

两棵树上的节点数目都在范围 [0, 100] 内
-104 <= Node.val <= 104

前置知识

公司

思路

关键点

代码

Java Code:


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

复杂度分析

令 n 为数组长度。

wenlong201807 commented 3 years ago

解题思路

如果完全相同的树,那么依据其特点:判断为关于y轴对称
所以要保证 
1.左节点 等于 右节点, 
2.左子树的左子节点 等于 右子树的右子节点
2.左子树的右子节点 等于 右子树的左子节点

代码块


var isSameTree = function (p, q) {
  if (p === null && q !== null) {
    return false
  } else if (p !== null && q === null) {
    return false
  } else if (p === null && q === null) {
    return true
  } else {
    return p.val === q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right)
  }
};

时间复杂度和空间复杂度

JK1452470209 commented 3 years ago

思路

dfs 对左右节点需使用&&操作 只有其中有一个false则不成立

代码

class Solution {
    public boolean isSameTree(TreeNode p, TreeNode q) {

        if (p == null && q == null) return true;
        if (p == null || q == null) return false;
        if (p.val != q.val) return false;
        return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
    }
}

复杂度

时间复杂度:O(N),N为树的节点数量

空间复杂度:O(h),h为树的高度

hewenyi666 commented 3 years ago

题目名称

100. 相同的树

题目链接

https://leetcode-cn.com/problems/same-tree/

题目思路

1.特例处理,先比较两个根节点: 如果两节点都为空,返回true; 如果两节点一个为空一个不为空,返回false; 如果两节点值不相同,返回false

2.如果两个节点值相同,比较左子树和右子树是否相同,这就进入了递归

code for Python3

class Solution:
    def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
        if not p and not q:
            return True
        elif not p or not q:
            return False
        elif p.val != q.val:
            return False
        else:
            return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)

复杂度分析

naomiwufzz commented 3 years ago

思路:先序遍历+递归

先序地看每个节点是否相等

(1)输入输出:输入是两个树的树节点,输出是节点是否相等

(2)递归出口:如果有node是none,要么两个树相等的时候都是none,要么一个none一个不是none,前者是true后者是false

(3)递归逻辑:要判断是否相等,要看当前节点相等,左节点相等、右节点相等

代码

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
        def preorder(p_node, q_node):
            # 先序地看p和q是否相等
            if not p_node and not q_node:
                return True
            if not p_node or not q_node:
                return False
            cur_same = p_node.val == q_node.val
            left_same = preorder(p_node.left, q_node.left)
            right_same = preorder(p_node.right, q_node.right)
            return cur_same and left_same and right_same
        return preorder(p, q)

复杂度分析

minuet-red commented 3 years ago

时间复杂度:O(N),N为树的节点数量

空间复杂度:O(h),h为树的高度

class Solution {
public:
    bool isSameTree(TreeNode* p, TreeNode* q) {
        if (p == nullptr || q == nullptr) return p == q;
        if (p->val != q->val)  return false;
        return isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
    }
};
Francis-xsc commented 3 years ago

思路

递归,判断左右子树是否相同

代码


class Solution {
public:
    bool isSameTree(TreeNode* p, TreeNode* q) {
        if(!p&&!q) 
            return true;
        if(!p||!q||p->val^q->val)
            return false;
        return isSameTree(p->left,q->left)&&isSameTree(p->right,q->right);
    }
};

复杂度分析

biscuit279 commented 3 years ago

思路:

递归,结束条件为节电树目不一致或值不相同

class Solution(object):
    def isSameTree(self, p, q):
        """
        :type p: TreeNode
        :type q: TreeNode
        :rtype: bool
        """
        if not p and not q :
            return True
        elif not p and q :
            return False
        elif p  and not q :
            return False
        elif p.val != q.val:
            return False
        else:
            return (self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right))

时间复杂度:O(N) 空间复杂度:O(H)

learning-go123 commented 3 years ago

思路

代码

Go Code:


/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func isSameTree(p *TreeNode, q *TreeNode) bool {
    if p == nil && q == nil {
        return true
    }
    if p == nil || q == nil {
        return false
    }

    if p.Val != q.Val {
        return false
    }

    return isSameTree(p.Left, q.Left) && isSameTree(p.Right, q.Right)
}

复杂度分析

令 n 为数组长度。

lilixikun commented 3 years ago

思路

遇到树、就是递归、判断左右子树是否相等

代码

var isSameTree = function(p, q) {
    if(p==null&&q==null){
        return true
    }
    if(p==null||q==null){
        return false
    }
    if(p.val==q.val){
        return isSameTree(p.left,q.left)&&isSameTree(p.right,q.right)
    }
    return false
};

复杂度

laurallalala commented 3 years ago

代码

class Solution(object):
    def isSameTree(self, p, q):
        """
        :type p: TreeNode
        :type q: TreeNode
        :rtype: bool
        """
        if not p and not q:
            return True
        elif not p or not q:
            return False
        isSame = True
        if p.val != q.val:
            return False
        isSame = isSame and self.isSameTree(p.left, q.left)
        isSame = isSame and self.isSameTree(p.right, q.right)
        return isSame

复杂度

mmboxmm commented 3 years ago

思路

二叉树总是递归

代码

class Solution {
    public boolean isSameTree(TreeNode p, TreeNode q) {
        if (p == null && q == null) return true;
        if (p == null || q == null) return false;

        return p.val == q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
    }
}

复杂度

AruSeito commented 3 years ago

思路

一套拳法:只考虑当前节点该干嘛。然后一递归。

var isSameTree = function(p, q) {

    function dg(root1,root2){
        if(root1 && !root2) return false;
        if(!root1 && root2) return false;
        if(!root1 && !root2) return true;
        return root1.val === root2.val && dg(root1.left,root2.left) && dg(root1.right,root2.right);
    }

    return dg(p,q);

};
xuezhongyuan commented 3 years ago

代码:

class Solution {
    public boolean isSameTree(TreeNode p,TreeNode q){
        if(p == null || q == null){
            return p == q;
        }

        if (p.val != q.val){
            return false;
        }

        return isSameTree(p.left,q.left) && isSameTree(p.right,q.right);

    }
}
shawncvv commented 3 years ago

思路

官方解题思路

代码

JavaScript Code

var isSameTree = function (p, q) {
  if (!p || !q) {
    return !p && !q;
  }
  return (
    p.val === q.val &&
    isSameTree(p.left, q.left) &&
    isSameTree(p.right, q.right)
  );
};

复杂度

chakochako commented 3 years ago
class Solution:
    def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
        if not p and not q:
            return True
        if not p or not q:
            return False
        return (p.val == q.val) and self.isSameTree(p.left,q.left) and self.isSameTree(p.right,q.right)
okbug commented 3 years ago

思路1

JS的转字符串方法

代码

语言:JavaScript

var isSameTree = function(p, q) {
    return JSON.stringify(p) === JSON.stringify(q);
};

思路2

递归,判断每个子树中是不是相同的,终止条件就是走到null,也就是叶子节点

代码

JavaScript

var isSameTree = function(p, q) {
    if (!p && !q) return true;
    if (!p || !q) return false;

    return (p.val === q.val) && isSameTree(p.left, q.left) && isSameTree(p.right, q.right); 
};

C++

class Solution {
public:
    bool isSameTree(TreeNode* p, TreeNode* q) {
        if (!q && !p) return true;
        if (!p || !q) return false;

        return isSameTree(p->left, q->left) && isSameTree(p->right, q->right) && (p->val == q->val);
    }
};