题目链接: https://leetcode.com/PRoblems/symmetric-tree/?tab=Description
题目描述:
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 3But the following
[1,2,2,null,3,null,3]
is not:1 / / 2 2 / / 3 3分别按照先左后右和先右后左的顺序进行DFS,比较对应节点的值是否相等
代码:
/** * 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==NULL||(root->left==NULL&&root->right==NULL)) return 1; else return DFS(root->left,root->right); } bool DFS(TreeNode* root1,TreeNode* root2) { if(root1==NULL&&root2==NULL) return 1; else if((root1==NULL&&root2!=NULL)||(root1!=NULL&&root2==NULL)) return 0; else if(root1->val!=root2->val) return 0; else return DFS(root1->left,root2->right)&&DFS(root1->right,root2->left); }};
新闻热点
疑难解答