topic
Given the root of a binary tree root
, check if it is axisymmetric.
Example 1:
Input: root = [1,2,2,3,4,4,3] Output: true
Example 2:
Input: root = [1,2,2,null,3,null,3] Output: false
hint:
- The number of nodes in the tree is
[1, 1000]
within the range -100 <= Node.val <= 100
answer
source code
/**
* 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) {
if (root == null) {
return true;
}
return isSymmetric(root.left, root.right);
}
public boolean isSymmetric(TreeNode node1, TreeNode node2) {
if (node1 == null || node2 == null) {
if (node1 == node2) {
return true;
} else {
return false;
}
}
if (node1.val != node2.val) {
return false;
}
return isSymmetric(node1.left, node2.right) && isSymmetric(node1.right, node2.left);
}
}
Summarize
Recursion is gradually used proficiently. In fact, I feel that its difficulty lies in summarizing the law of the algorithm, that is, when to recurse. We all know that the recursive function should include recursion and end judgment, so I regard this question as judging whether the binary tree corresponding to the two nodes is symmetrical about the root node. When the left and right child nodes are empty and the values are not equal, the function returns, otherwise continue to Next traversal, here it should be noted that one node corresponds to two child nodes, so one function contains two recursive functions.