LeetCode - Symmetric Tree

问题:判断二叉树是否为镜像二叉树
分析:递归判断,根节点单独判断,然后递归左结点和右结点,之后每次一起递归左结点的左结点和右结点的右结点比较,左结点的右结点和右结点的左结点比较。

 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 isSymmetric(TreeNode *root) {
13         if (!root || (!root->left && !root->right))
14             return true;
15         return dfs(root->left, root->right);
16     }
17     
18     bool dfs(TreeNode *left, TreeNode *right)
19     {
20         if (!left && !right)
21             return true;
22         if ((!left && right) || (left && !right) || (left->val != right->val)) 
23             return false;
24         return dfs(left->left, right->right) && dfs(left->right, right->left);
25     }
26 };

 

posted @ 2015-04-02 23:21  bournet  阅读(116)  评论(0编辑  收藏  举报