|
41 | 41 |
|
42 | 42 | <!-- 这里可写通用的实现逻辑 -->
|
43 | 43 |
|
| 44 | +**方法一:递归** |
| 45 | + |
| 46 | +我们设计一个函数 $dfs(root1, root2)$,用于判断两个二叉树是否对称。答案即为 $dfs(root, root)$。 |
| 47 | + |
| 48 | +函数 $dfs(root1, root2)$ 的逻辑如下: |
| 49 | + |
| 50 | +- 如果 $root1$ 和 $root2$ 都为空,则两个二叉树对称,返回 `true`; |
| 51 | +- 如果 $root1$ 和 $root2$ 中只有一个为空,或者 $root1.val \neq root2.val$,则两个二叉树不对称,返回 `false`; |
| 52 | +- 否则,判断 $root1$ 的左子树和 $root2$ 的右子树是否对称,以及 $root1$ 的右子树和 $root2$ 的左子树是否对称,这里使用了递归。 |
| 53 | + |
| 54 | +时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是二叉树的节点数。 |
| 55 | + |
44 | 56 | <!-- tabs:start -->
|
45 | 57 |
|
46 | 58 | ### **Python3**
|
|
55 | 67 | # self.left = left
|
56 | 68 | # self.right = right
|
57 | 69 | class Solution:
|
58 |
| - def isSymmetric(self, root: TreeNode) -> bool: |
| 70 | + def isSymmetric(self, root: Optional[TreeNode]) -> bool: |
59 | 71 | def dfs(root1, root2):
|
60 | 72 | if root1 is None and root2 is None:
|
61 | 73 | return True
|
@@ -120,17 +132,42 @@ class Solution {
|
120 | 132 | class Solution {
|
121 | 133 | public:
|
122 | 134 | bool isSymmetric(TreeNode* root) {
|
| 135 | + function<bool(TreeNode*, TreeNode*)> dfs = [&](TreeNode* root1, TreeNode* root2) -> bool { |
| 136 | + if (!root1 && !root2) return true; |
| 137 | + if (!root1 || !root2 || root1->val != root2->val) return false; |
| 138 | + return dfs(root1->left, root2->right) && dfs(root1->right, root2->left); |
| 139 | + }; |
123 | 140 | return dfs(root, root);
|
124 | 141 | }
|
125 |
| - |
126 |
| - bool dfs(TreeNode* root1, TreeNode* root2) { |
127 |
| - if (!root1 && !root2) return 1; |
128 |
| - if (!root1 || !root2 || root1->val != root2->val) return 0; |
129 |
| - return dfs(root1->left, root2->right) && dfs(root1->right, root2->left); |
130 |
| - } |
131 | 142 | };
|
132 | 143 | ```
|
133 | 144 |
|
| 145 | +### **Go** |
| 146 | +
|
| 147 | +```go |
| 148 | +/** |
| 149 | + * Definition for a binary tree node. |
| 150 | + * type TreeNode struct { |
| 151 | + * Val int |
| 152 | + * Left *TreeNode |
| 153 | + * Right *TreeNode |
| 154 | + * } |
| 155 | + */ |
| 156 | +func isSymmetric(root *TreeNode) bool { |
| 157 | + var dfs func(*TreeNode, *TreeNode) bool |
| 158 | + dfs = func(root1, root2 *TreeNode) bool { |
| 159 | + if root1 == nil && root2 == nil { |
| 160 | + return true |
| 161 | + } |
| 162 | + if root1 == nil || root2 == nil || root1.Val != root2.Val { |
| 163 | + return false |
| 164 | + } |
| 165 | + return dfs(root1.Left, root2.Right) && dfs(root1.Right, root2.Left) |
| 166 | + } |
| 167 | + return dfs(root, root) |
| 168 | +} |
| 169 | +``` |
| 170 | + |
134 | 171 | ### **TypeScript**
|
135 | 172 |
|
136 | 173 | ```ts
|
|
0 commit comments