Leetcode 100: Same Tree
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 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * public int val; 5 * public TreeNode left; 6 * public TreeNode right; 7 * public TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 public bool IsSameTree(TreeNode p, TreeNode q) { 12 if (p == null || q == null) 13 { 14 return p == null && q == null; 15 } 16 17 return p.val == q.val && IsSameTree(p.left, q.left) && IsSameTree(p.right, q.right); 18 } 19 }

浙公网安备 33010602011771号