101. Symmetric Tree

问题
Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).

递归root1的左子节点和root2的右子节点以及root2的左子节点以及root1的右子节点。如两者不相等则返回false。
如果传入的两个数值有一个为null,则两者不相等时返回false。反之返回true。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/**
* 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 isSymmetric(root,root);
}

public boolean isSymmetric(TreeNode root1, TreeNode root2){
if ( root1 == null || root2 == null ){
if(root1 == root2){return true;}
else{return false;}
}
if ( root1.val == root2.val ){
return isSymmetric(root1.left,root2.right) && isSymmetric(root1.right,root2.left);
}
else{
return false;
}
}
}
Author

Xander

Posted on

2022-04-13

Updated on

2022-04-13

Licensed under

Comments