Skip to content

Latest commit

 

History

History
71 lines (60 loc) · 1.39 KB

100. Same Tree.md

File metadata and controls

71 lines (60 loc) · 1.39 KB

leetcode Daily Challenge on July 13th, 2020.

leetcode-cn Daily Challenge on August 7th, 2020.


Difficulty : Easy

Related Topics : DFSTree


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

Solution

  • mine
    • Java
      • DFS & Recursion Runtime: 0 ms, faster than 100.00%, Memory Usage: 38.7 MB, less than 11.47% of Java online submissions
        // O(N)time
        // O(D)space
        public boolean isSameTree(TreeNode p, TreeNode q) {
            if(p == null) return q == null;
            if(q == null) return p == null;
            return p.val == q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
        }