题目链接:点击打开链接
题目大意:略
解题思路:略
相关企业
- 字节跳动
- 谷歌(Google)
- 微软(Microsoft)
- 亚马逊(Amazon)
- 优步(Uber)
- Paypal
- 彭博(Bloomberg)
AC 代码
- Java
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
// 解决方案(1)
class Solution {
private boolean ok = true;
public boolean isSymmetric(TreeNode root) {
if (null == root || root.left == null && root.right == null) {
return true;
}
if (root.left == null || root.right == null) {
return false;
}
dfs(root.left, root.right);
return ok;
}
private void dfs(TreeNode l, TreeNode r) {
if (!ok) {
return;
}
if (null == l && null == r) return;
if (null == l || null == r) {
ok = false;
return;
}
if (l.val != r.val) {
ok = false;
return;
}
dfs(l.left, r.right);
dfs(l.right, r.left);
}
}
// 解决方案(2)
class Solution {
public boolean isSymmetric(TreeNode root) {
return root == null || recur(root.left, root.right);
}
boolean recur(TreeNode L, TreeNode R) {
if(L == null && R == null) return true;
if(L == null || R == null || L.val != R.val) return false;
return recur(L.left, R.right) && recur(L.right, R.left);
}
}
- C++
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isSymmetric(TreeNode* root) {
return root == nullptr || recur(root->left, root->right);
}
private:
bool recur(TreeNode* L, TreeNode* R) {
if(L == nullptr && R == nullptr) return true;
if(L == nullptr || R == nullptr || L->val != R->val) return false;
return recur(L->left, R->right) && recur(L->right, R->left);
}
};