100. Same Tree Easy

@problem@discussion
#Tree#Depth-First Search#Breadth-First Search#Binary Tree



1/**
2 * [100] Same Tree
3 *
4 * Given the roots of two binary trees p and q, write a function to check if they are the same or not.
5 * Two binary trees are considered the same if they are structurally identical, and the nodes have the same value.
6 *  
7 * Example 1:
8 * <img alt="" src="https://assets.leetcode.com/uploads/2020/12/20/ex1.jpg" style="width: 622px; height: 182px;" />
9 * Input: p = [1,2,3], q = [1,2,3]
10 * Output: true
11 * 
12 * Example 2:
13 * <img alt="" src="https://assets.leetcode.com/uploads/2020/12/20/ex2.jpg" style="width: 382px; height: 182px;" />
14 * Input: p = [1,2], q = [1,null,2]
15 * Output: false
16 * 
17 * Example 3:
18 * <img alt="" src="https://assets.leetcode.com/uploads/2020/12/20/ex3.jpg" style="width: 622px; height: 182px;" />
19 * Input: p = [1,2,1], q = [1,1,2]
20 * Output: false
21 * 
22 *  
23 * Constraints:
24 * 
25 * The number of nodes in both trees is in the range [0, 100].
26 * -10^4 <= Node.val <= 10^4
27 * 
28 */
29pub struct Solution {}
30#[allow(unused_imports)]
31use crate::util::tree::{TreeNode, to_tree};
32
33// problem: https://leetcode.com/problems/same-tree/
34// discuss: https://leetcode.com/problems/same-tree/discuss/?currentPage=1&orderBy=most_votes&query=
35
36// submission codes start here
37
38// Definition for a binary tree node.
39// #[derive(Debug, PartialEq, Eq)]
40// pub struct TreeNode {
41//   pub val: i32,
42//   pub left: Option<Rc<RefCell<TreeNode>>>,
43//   pub right: Option<Rc<RefCell<TreeNode>>>,
44// }
45// 
46// impl TreeNode {
47//   #[inline]
48//   pub fn new(val: i32) -> Self {
49//     TreeNode {
50//       val,
51//       left: None,
52//       right: None
53//     }
54//   }
55// }
56use std::rc::Rc;
57use std::cell::RefCell;
58impl Solution {
59    pub fn is_same_tree(p: Option<Rc<RefCell<TreeNode>>>, q: Option<Rc<RefCell<TreeNode>>>) -> bool {
60        match (p, q) {
61            (None, None) => true,
62            (Some(p), Some(q)) => {
63                let p = p.borrow();
64                let q = q.borrow();
65                p.val == q.val
66                    && Self::is_same_tree(p.left.clone(), q.left.clone())
67                    && Self::is_same_tree(p.right.clone(), q.right.clone())
68            }
69            _ => false,
70        }
71    }
72}
73
74// submission codes end
75
76#[cfg(test)]
77mod tests {
78    use super::*;
79    use crate::tree;
80
81    #[test]
82    fn test_100() {
83        assert!(Solution::is_same_tree(tree![1,2,3], tree![1,2,3]));
84    }
85}
86


Back
© 2025 bowen.ge All Rights Reserved.