https://leetcode.com/problems/merge-two-binary-trees/description/
When I submit the solution below, sometimes it failed for the test case:
Input data:
[1,3,2,5]
[2,1,3,null,4,null,7]
Actual
✔ runtime: 0 ms
✘ answer: [3,4,5,5,4,7]
✔ stdout: ''
Expected
✔ runtime: 0 ms
✔ answer: [3,4,5,5,4,null,7]
✔ stdout: ''
while when I try to submit it again, it may got AC:
Input data:
[1,3,2,5]
[2,1,3,null,4,null,7]
Actual
✔ runtime: 0 ms
✔ answer: [3,4,5,5,4,null,7]
✔ stdout: ''
Expected
✔ runtime: 0 ms
✔ answer: [3,4,5,5,4,null,7]
✔ stdout: ''
// 2018-12-26 11:41
// @lc id=617 lang=rust
use std::cell::RefCell;
use std::rc::Rc;
impl Solution {
pub fn merge_trees(
t1: Option<Rc<RefCell<TreeNode>>>,
t2: Option<Rc<RefCell<TreeNode>>>,
) -> Option<Rc<RefCell<TreeNode>>> {
if t1 == None && t2 == None {
return None;
}
let t1_val = {
if let Some(ref x) = t1 {
x.clone().borrow().val
} else {
0
}
};
let t2_val = {
if let Some(ref x) = t2 {
x.clone().borrow().val
} else {
0
}
};
let root = Rc::new(RefCell::new(TreeNode::new(t1_val + t2_val)));
let (t1_left, t1_right) = {
if let Some(ref x) = t1 {
(x.borrow().left.clone(), x.borrow().right.clone())
} else {
(None, None)
}
};
let (t2_left, t2_right) = {
if let Some(ref x) = t2 {
(x.borrow().left.clone(), x.borrow().right.clone())
} else {
(None, None)
}
};
root.borrow_mut().left = Solution::merge_trees(t1_left, t2_left);
root.borrow_mut().right = Solution::merge_trees(t1_right, t2_right);
return Some(root);
}
}