Blind 75
Same Tree
- Problem
- LC 100
- Category
- Tree
- File
- blind75_LC100SameTree.java
- Path
- pkg5leetcode/blind75/blind75_LC100SameTree.java
- Package
- pkg5leetcode.blind75
- Command
- java pkg5leetcode/blind75/blind75_LC100SameTree.java
- Approach
- Recursive compare values and subtrees.
- Complexity
- Time O(n), Space O(h)
There is no in-browser runner. This is the file from the curriculum, unchanged.
1package pkg5leetcode.blind75;2 3/*4 * Same Tree | LC 1005 * APPROACH: Recursive compare values and subtrees.6 * COMPLEXITY: Time O(n), Space O(h)7 */8public class blind75_LC100SameTree {9 /** Same shape as pkg5leetcode/common/TreeNode.java (nested for single-file runs). */10 11 static class TreeNode {12 int val;13 TreeNode left, right;14 TreeNode(int val) { this.val = val; }15 }16 17 static boolean isSameTree(TreeNode p, TreeNode q) {18 if (p == null || q == null) return p == q;19 return p.val == q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right);20 }21 22 public static void main(String[] args) {23 TreeNode a = new TreeNode(1); a.left = new TreeNode(2); a.right = new TreeNode(3);24 TreeNode b = new TreeNode(1); b.left = new TreeNode(2); b.right = new TreeNode(3);25 check(isSameTree(a, b), "case1");26 TreeNode c = new TreeNode(1); c.left = new TreeNode(2);27 TreeNode d = new TreeNode(1); d.right = new TreeNode(2);28 check(!isSameTree(c, d), "case2");29 System.out.println("all tests passed");30 }31 32 static void check(boolean cond, String name) {33 if (!cond) throw new AssertionError("FAILED: " + name);34 System.out.println(" PASS " + name);35 }36}