【LeetCode】Symmetric Tree

101. Symmetric Tree

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

For example, this 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:

    1
   / \
  2   2
   \   \
   3    3

 

Note:
Bonus points if you could solve it both recursively and iteratively.

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     struct TreeNode *left;
 6  *     struct TreeNode *right;
 7  * };
 8  */
 9 //比较对称节点值是否相同
10 bool isSameCompare(struct TreeNode* root, int value)
11 {
12     if(root->val == value)
13     {
14         return true;
15     }
16     else
17     {
18         return false;
19     }
20 }
21 //比较结构是否对称
22 bool isSameLeft(struct TreeNode* rootLeft, struct TreeNode* rootRight)
23 {
24     //结构不同返回false
25     if((!rootLeft && rootRight) || (rootLeft && !rootRight))
26     {
27         return false;
28     }
29     //叶子节点结束证明已比较的是对称的
30     if(!rootLeft && !rootRight)
31     {
32         return true;
33     }
34     if( !isSameCompare(rootRight, rootLeft->val) )
35     {
36         return false;
37     }
38     //递归求根节点下的左子树和右子树是否对称
39     return (isSameLeft(rootLeft->left, rootRight->right) && isSameLeft(rootLeft->right, rootRight->left));
40 }
41 bool isSymmetric(struct TreeNode* root) 
42 {
43     if(!root)
44     {
45         return true;
46     }
47     return isSameLeft(root->left, root->right);
48 }

已提供注释,如有疑惑欢迎联系!

posted @ 2019-03-27 21:28  梅花五瓣  阅读(135)  评论(0)    收藏  举报