当前位置:网站首页>LeetCode-101. Symmetric Tree

LeetCode-101. Symmetric Tree

2022-08-10 16:03:00 51CTO


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
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.

 

But the following ​​[1,2,2,null,3,null,3]​​ is not:

      
      
1
/ \
2 2
\ \
3 3
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.

 

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

题解:

      
      
class Solution {
public:
bool bothAreSymmetric ( TreeNode * a, TreeNode * b) {
if ( a == NULL && b == NULL) {
return true;
}
else if ( a != NULL && b != NULL && a -> val == b -> val) {
return bothAreSymmetric( a -> left, b -> right) && bothAreSymmetric( a -> right, b -> left);
}
else {
return false;
}
}
bool isSymmetric( TreeNode * root) {
if ( root == NULL) {
return true;
}
if ( root -> left == NULL || root -> right == NULL) {
return root -> left == root -> right;
}
return root -> left -> val == root -> right -> val && bothAreSymmetric( root -> left -> right, root -> right -> left) && bothAreSymmetric( root -> left -> left, root -> right -> right);
}
};
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.

 

原网站

版权声明
本文为[51CTO]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/222/202208101533305158.html