617. Merge Two Binary Trees Easy

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



1/**
2 * [617] Merge Two Binary Trees
3 *
4 * You are given two binary trees root1 and root2.
5 * Imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not. You need to merge the two trees into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of the new tree.
6 * Return the merged tree.
7 * Note: The merging process must start from the root nodes of both trees.
8 *  
9 * Example 1:
10 * <img alt="" src="https://assets.leetcode.com/uploads/2021/02/05/merge.jpg" style="width: 600px; height: 163px;" />
11 * Input: root1 = [1,3,2,5], root2 = [2,1,3,null,4,null,7]
12 * Output: [3,4,5,5,4,null,7]
13 * 
14 * Example 2:
15 * 
16 * Input: root1 = [1], root2 = [1,2]
17 * Output: [2,2]
18 * 
19 *  
20 * Constraints:
21 * 
22 * 	The number of nodes in both trees is in the range [0, 2000].
23 * 	-10^4 <= Node.val <= 10^4
24 * 
25 */
26pub struct Solution {}
27use crate::util::tree::{TreeNode, to_tree};
28
29// problem: https://leetcode.com/problems/merge-two-binary-trees/
30// discuss: https://leetcode.com/problems/merge-two-binary-trees/discuss/?currentPage=1&orderBy=most_votes&query=
31
32// submission codes start here
33
34// Definition for a binary tree node.
35// #[derive(Debug, PartialEq, Eq)]
36// pub struct TreeNode {
37//   pub val: i32,
38//   pub left: Option<Rc<RefCell<TreeNode>>>,
39//   pub right: Option<Rc<RefCell<TreeNode>>>,
40// }
41// 
42// impl TreeNode {
43//   #[inline]
44//   pub fn new(val: i32) -> Self {
45//     TreeNode {
46//       val,
47//       left: None,
48//       right: None
49//     }
50//   }
51// }
52use std::rc::Rc;
53use std::cell::RefCell;
54impl Solution {
55    pub fn merge_trees(root1: Option<Rc<RefCell<TreeNode>>>, root2: Option<Rc<RefCell<TreeNode>>>) -> Option<Rc<RefCell<TreeNode>>> {
56        Some(Rc::new(RefCell::new(TreeNode::new(0))))
57    }
58}
59
60// submission codes end
61
62#[cfg(test)]
63mod tests {
64    use super::*;
65
66    #[test]
67    fn test_617() {
68    }
69}
70


Back
© 2025 bowen.ge All Rights Reserved.