Symmetric binary tree
Please implement a function to determine whether a binary tree is symmetric. If a binary tree is the same as its mirror image, then it is symmetric.
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 symmetry:
1
/ \
2 2
\ \
3 3
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
Limit:
0 <= number of nodes <= 1000
analysis
Simple tree traversal
solution
A tree is divided into two trees and compared on the premise that their root nodes are the same: the left node of the A tree and the right node of the B tree; the right node of the A tree and the left node of the B tree;
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
bool judge(struct TreeNode* A, struct TreeNode * B){
// 如果A B都为空了,得到true值,
if(A == NULL && B == NULL)
return true;
// 在AB同空之后,判断A或者B是否有一方为空,如果是,则返回false,确保程序的鲁棒性,否则继续往下执行则会报错,空节点没有相关属性。
if(A == NULL || B == NULL)
return false;
// A与B的关系,如果没有上诉的递归出口,下面这段程序将会陷入死循环。
if(A->val != B->val)
return false;
else{
return judge(A->left, B->right) && judge(A->right, B->left);
}
}
bool isSymmetric(struct TreeNode* root){
if(root == NULL){
return true;
}
struct TreeNode * p = root->right;
struct TreeNode * q = root->left;
return judge(q, p);
}