Description
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
Analysis
最直接的方法是递归对称遍历整棵树。但要主要处理好NULL
的问题,具体而言,包含两方面:
- 空树
root == NULL
- 叶结点
node->next == NULL
Code
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isSymmetric(TreeNode* root) {
if (!root) return true;
return judge(root->left,root->right);
}
private:
bool judge(TreeNode* l, TreeNode* r){
if (!l && !r) return true;
if (!l || !r) return false;
return (l->val == r->val) && judge(l->left,r->right) && judge(l->right,r->left);
}
};
Appendix
- Link: https://leetcode.com/problems/symmetric-tree/
- Run Time: 6ms