Skip to content

Commit

Permalink
feat: add solutions to lc problem: No.0101 (#3910)
Browse files Browse the repository at this point in the history
No.0101.Symmetric Tree
  • Loading branch information
yanglbme authored Dec 31, 2024
1 parent 398146b commit e7c5da6
Show file tree
Hide file tree
Showing 26 changed files with 339 additions and 934 deletions.
165 changes: 56 additions & 109 deletions solution/0100-0199/0101.Symmetric Tree/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,13 +58,13 @@ tags:

### 方法一:递归

我们设计一个函数 $dfs(root1, root2)$,用于判断两个二叉树是否对称。答案即为 $dfs(root, root)$。
我们设计一个函数 $\textit{dfs}(\textit{root1}, \textit{root2})$,用于判断两个二叉树是否对称。答案即为 $\textit{dfs}(\textit{root.left}, \textit{root.right})$。

函数 $dfs(root1, root2)$ 的逻辑如下:
函数 $\textit{dfs}(\textit{root1}, \textit{root2})$ 的逻辑如下:

- 如果 $root1$ 和 $root2$ 都为空,则两个二叉树对称,返回 `true`
- 如果 $root1$ 和 $root2$ 中只有一个为空,或者 $root1.val \neq root2.val$,则两个二叉树不对称,返回 `false`
- 否则,判断 $root1$ 的左子树和 $root2$ 的右子树是否对称,以及 $root1$ 的右子树和 $root2$ 的左子树是否对称,这里使用了递归。
- 如果 $\textit{root1}$ 和 $\textit{root2}$ 都为空,则两个二叉树对称,返回 `true`
- 如果 $\textit{root1}$ 和 $\textit{root2}$ 中只有一个为空,或者 $\textit{root1.val} \neq \textit{root2.val}$
- 否则,判断 $\textit{root1}$ 的左子树和 $\textit{root2}$ 的右子树是否对称,以及 $\textit{root1}$ 的右子树和 $\textit{root2}$ 的左子树是否对称,这里使用了递归。

时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是二叉树的节点数。

Expand All @@ -81,14 +81,14 @@ tags:
# self.right = right
class Solution:
def isSymmetric(self, root: Optional[TreeNode]) -> bool:
def dfs(root1, root2):
if root1 is None and root2 is None:
def dfs(root1: Optional[TreeNode], root2: Optional[TreeNode]) -> bool:
if root1 == root2:
return True
if root1 is None or root2 is None or root1.val != root2.val:
return False
return dfs(root1.left, root2.right) and dfs(root1.right, root2.left)

return dfs(root, root)
return dfs(root.left, root.right)
```

#### Java
Expand All @@ -111,11 +111,11 @@ class Solution:
*/
class Solution {
public boolean isSymmetric(TreeNode root) {
return dfs(root, root);
return dfs(root.left, root.right);
}

private boolean dfs(TreeNode root1, TreeNode root2) {
if (root1 == null && root2 == null) {
if (root1 == root2) {
return true;
}
if (root1 == null || root2 == null || root1.val != root2.val) {
Expand Down Expand Up @@ -143,12 +143,16 @@ class Solution {
class Solution {
public:
bool isSymmetric(TreeNode* root) {
function<bool(TreeNode*, TreeNode*)> dfs = [&](TreeNode* root1, TreeNode* root2) -> bool {
if (!root1 && !root2) return true;
if (!root1 || !root2 || root1->val != root2->val) return false;
auto dfs = [&](this auto&& dfs, TreeNode* root1, TreeNode* root2) -> bool {
if (root1 == root2) {
return true;
}
if (!root1 || !root2 || root1->val != root2->val) {
return false;
}
return dfs(root1->left, root2->right) && dfs(root1->right, root2->left);
};
return dfs(root, root);
return dfs(root->left, root->right);
}
};
```
Expand All @@ -165,17 +169,17 @@ public:
* }
*/
func isSymmetric(root *TreeNode) bool {
var dfs func(*TreeNode, *TreeNode) bool
var dfs func(root1, root2 *TreeNode) bool
dfs = func(root1, root2 *TreeNode) bool {
if root1 == nil && root2 == nil {
if root1 == root2 {
return true
}
if root1 == nil || root2 == nil || root1.Val != root2.Val {
return false
}
return dfs(root1.Left, root2.Right) && dfs(root1.Right, root2.Left)
}
return dfs(root, root)
return dfs(root.Left, root.Right)
}
```

Expand All @@ -196,17 +200,16 @@ func isSymmetric(root *TreeNode) bool {
* }
*/

const dfs = (root1: TreeNode | null, root2: TreeNode | null) => {
if (root1 == root2) {
return true;
}
if (root1 == null || root2 == null || root1.val != root2.val) {
return false;
}
return dfs(root1.left, root2.right) && dfs(root1.right, root2.left);
};

function isSymmetric(root: TreeNode | null): boolean {
const dfs = (root1: TreeNode | null, root2: TreeNode | null): boolean => {
if (root1 === root2) {
return true;
}
if (!root1 || !root2 || root1.val !== root2.val) {
return false;
}
return dfs(root1.left, root2.right) && dfs(root1.right, root2.left);
};
return dfs(root.left, root.right);
}
```
Expand Down Expand Up @@ -235,23 +238,25 @@ function isSymmetric(root: TreeNode | null): boolean {
use std::cell::RefCell;
use std::rc::Rc;
impl Solution {
fn dfs(root1: &Option<Rc<RefCell<TreeNode>>>, root2: &Option<Rc<RefCell<TreeNode>>>) -> bool {
if root1.is_none() && root2.is_none() {
return true;
}
if root1.is_none() || root2.is_none() {
return false;
pub fn is_symmetric(root: Option<Rc<RefCell<TreeNode>>>) -> bool {
fn dfs(root1: Option<Rc<RefCell<TreeNode>>>, root2: Option<Rc<RefCell<TreeNode>>>) -> bool {
match (root1, root2) {
(Some(node1), Some(node2)) => {
let node1 = node1.borrow();
let node2 = node2.borrow();
node1.val == node2.val
&& dfs(node1.left.clone(), node2.right.clone())
&& dfs(node1.right.clone(), node2.left.clone())
}
(None, None) => true,
_ => false,
}
}
let node1 = root1.as_ref().unwrap().borrow();
let node2 = root2.as_ref().unwrap().borrow();
node1.val == node2.val
&& Self::dfs(&node1.left, &node2.right)
&& Self::dfs(&node1.right, &node2.left)
}

pub fn is_symmetric(root: Option<Rc<RefCell<TreeNode>>>) -> bool {
let node = root.as_ref().unwrap().borrow();
Self::dfs(&node.left, &node.right)
match root {
Some(root) => dfs(root.borrow().left.clone(), root.borrow().right.clone()),
None => true,
}
}
}
```
Expand All @@ -272,79 +277,21 @@ impl Solution {
* @return {boolean}
*/
var isSymmetric = function (root) {
function dfs(root1, root2) {
if (!root1 && !root2) return true;
if (!root1 || !root2 || root1.val != root2.val) return false;
const dfs = (root1, root2) => {
if (root1 === root2) {
return true;
}
if (!root1 || !root2 || root1.val !== root2.val) {
return false;
}
return dfs(root1.left, root2.right) && dfs(root1.right, root2.left);
}
return dfs(root, root);
};
return dfs(root.left, root.right);
};
```

<!-- tabs:end -->

<!-- solution:end -->

<!-- solution:start -->

### 方法二

<!-- tabs:start -->

#### Rust

```rust
// Definition for a binary tree node.
// #[derive(Debug, PartialEq, Eq)]
// pub struct TreeNode {
// pub val: i32,
// pub left: Option<Rc<RefCell<TreeNode>>>,
// pub right: Option<Rc<RefCell<TreeNode>>>,
// }
//
// impl TreeNode {
// #[inline]
// pub fn new(val: i32) -> Self {
// TreeNode {
// val,
// left: None,
// right: None
// }
// }
// }
use std::cell::RefCell;
use std::collections::VecDeque;
use std::rc::Rc;
impl Solution {
pub fn is_symmetric(root: Option<Rc<RefCell<TreeNode>>>) -> bool {
let root = root.unwrap();
let mut node = root.as_ref().borrow_mut();
let mut queue = VecDeque::new();
queue.push_back([node.left.take(), node.right.take()]);
while let Some([root1, root2]) = queue.pop_front() {
if root1.is_none() && root2.is_none() {
continue;
}
if root1.is_none() || root2.is_none() {
return false;
}
if let (Some(node1), Some(node2)) = (root1, root2) {
let mut node1 = node1.as_ref().borrow_mut();
let mut node2 = node2.as_ref().borrow_mut();
if node1.val != node2.val {
return false;
}
queue.push_back([node1.left.take(), node2.right.take()]);
queue.push_back([node1.right.take(), node2.left.take()]);
}
}
true
}
}
```

<!-- tabs:end -->

<!-- solution:end -->

<!-- problem:end -->
Loading

0 comments on commit e7c5da6

Please sign in to comment.