Table of contents
The sword points to Offer 28. Symmetric binary tree
The sword points to Offer 28. Symmetric binary tree
Please implement a function to determine whether a binary tree is symmetrical. A binary tree is symmetrical if it is the same as its mirror image.
For example, the binary tree [1,2,2,3,4,4,3] is symmetric.
1
/ \
2 2
/ \ / \
3 4 4 3
But the following [1,2,2,null,3,null,3] is not mirror symmetric:
1
/ \
2 2
\ \
3 3Example 1:
Input: root = [1,2,2,3,4,4,3] Output: trueExample 2:
Input: root = [1,2,2,null,3,null,3] Output: falselimit:
0 <= 节点个数 <= 1000
题解:
- First determine whether the root node is empty, and return true if it is empty.
- Then call the fun method and pass in the left child node and right child node of the root node for judgment.
The logic of the fun method is:
- If A and B are both empty, return true;
- If either A or B is empty or the values are not equal, false is returned;
- Otherwise, recursively determine whether the left child node of A and the right child node of B are symmetrical, and whether the right child node of A and the left child node of B are symmetrical.
- Finally, the results are returned layer by layer through recursion, and a judgment result of whether it is symmetrical is obtained.
The time complexity is O(n)
代码:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public boolean isSymmetric(TreeNode root) { if(root==null) return true; return fun(root.left,root.right); } public boolean fun(TreeNode A,TreeNode B){ if(A==null&&B==null) return true; if(A==null||B==null||A.val!=B.val) return false; return fun(A.left,B.right)&&fun(A.right,B.left); } }
运行结果: