[LeetCode] Symmetric Tree
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree is symmetric:
1 / \ 2 2 / \ / \ 3 4 4 3
But the following is not:
1 / \ 2 2 \ \ 3 3
Note:
Bonus points if you could solve it both recursively and iteratively.
递归,保存左右两个节点,然后判断leftNode->left和rightNode->right,以及leftNode->right和rightNode->left。如此不断递归
1 /** 2 * Definition for binary tree 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 bool check(TreeNode *leftNode, TreeNode *rightNode) 13 { 14 if (leftNode == NULL && rightNode == NULL) 15 return true; 16 17 if (leftNode == NULL || rightNode == NULL) 18 return false; 19 20 return leftNode->val == rightNode->val && check(leftNode->left, rightNode->right) && 21 check(leftNode->right, rightNode->left); 22 } 23 24 bool isSymmetric(TreeNode *root) { 25 // Start typing your C/C++ solution below 26 // DO NOT write int main() function 27 if (root == NULL) 28 return true; 29 30 return check(root->left, root->right); 31 } 32 };