leetcode101回文树

101. Symmetric Tree

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

 

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

    1
   / \
  2   2
   \   \
   3    3

 

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

题意:判断树是否镜像(类似回文?)

思路:双路递归?根左右与根右左两种遍历方式同时进行,复杂度O(n)

 1 /**
 2  * Definition for a binary tree node.
 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 
11 bool dfs(TreeNode* l,TreeNode* r){
12     if(l==NULL&&r==NULL)return true;
13     if(l!=NULL&&r!=NULL){
14         if(l->val!=r->val)return false;
15         if(dfs(l->left,r->right)==false)return false;
16         if(dfs(l->right,r->left)==false)return false;
17         return true;
18     }
19     return false;
20 }
21 
22 class Solution {
23 public:
24     bool isSymmetric(TreeNode* root) {
25         return dfs(root,root);
26     }
27 };
View Code

 

posted @ 2017-05-21 14:36  poluner  阅读(71)  评论(0编辑  收藏  举报