ð101. 对称äºåæ
2022幎6æ9æ¥
- algorithm
ð101. 对称äºåæ
éŸåºŠ: ð
é®é¢æè¿°
è§£æ³ 1 - éåœ
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean isSymmetric(TreeNode root) {
// æè·¯:
// éåœ
// äžçšæ³æä¹åïŒåå°åªéèªç¶å°±ååºæ¥äº
return mySol(root.left, root.right);
}
private boolean mySol(TreeNode left, TreeNode right) {
// éåœç»æ¢æ¡ä»¶
if(left == null && right == null) {
return true;
}
if(left == null || right == null) {
return false;
}
// left != null && right != null
if(left.val != right.val) {
return false;
}
// left.val == right.val
return mySol(left.left, right.right) && mySol(left.right, right.left);
}
}
èŸåº 1
è§£æ³ 2 - è¿ä»£
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean isSymmetric(TreeNode root) {
// æè·¯ïŒ
// è¿ä»£ - åå© èŸ
å©æ
LinkedList<TreeNode> stack = new LinkedList<>(); // äžæ¬¡åæ¶åå·Šå³èç¹
stack.push(root.left);
stack.push(root.right);
while(!stack.isEmpty()) {
TreeNode right = stack.pop();
TreeNode left = stack.pop();
// é»èŸå€æ
if(left == null && right == null) {
continue;
} else if(left == null || right == null) {
return false;
} else if(left.val != right.val) {
return false;
} else {
stack.push(left.left);
stack.push(right.right);
stack.push(left.right);
stack.push(right.left);
}
}
return true;
}
}