Symmetric Tree

2014.1.1 01:12

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

Solution:

  Well..., I guess it's the new year 2014 now, and I've been writing blogs all night. Happy new year to those who are reading this article. Greetings from 2014, Beijing, China.

  To check if a tree is symmetric, you need to compare the corresponding nodes one pair at a time, in a recursive way.

  A pair at a time, therefore you need two TreeNode parameters in the recursive function.

  Time complexity is O(n), space complexity is O(1), where n is the number of nodes in the tree.

Accepted code:

 1 //#define __MAIN__
 2 
 3 #ifdef __MAIN__
 4 #include <cstdio>
 5 #include <cstdlib>
 6 using namespace std;
 7 #endif
 8 
 9 /**
10  * Definition for binary tree
11  * struct TreeNode {
12  *     int val;
13  *     TreeNode *left;
14  *     TreeNode *right;
15  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
16  * };
17  */
18 
19 #ifdef __MAIN__
20 struct TreeNode {
21     int val;
22     TreeNode *left;
23     TreeNode *right;
24     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
25 };
26 #endif
27 
28 class Solution {
29 public:
30     bool isSymmetric(TreeNode *root) {
31         // Note: The Solution object is instantiated only once and is reused by each test case.
32         if(root == nullptr){
33             return true;
34         }
35         return isMirror(root->left, root->right);
36     }
37 private:
38     bool isMirror(TreeNode *ra, TreeNode *rb) {
39         if(ra == nullptr && rb == nullptr){
40             return true;
41         }
42         
43         if(ra == nullptr || rb == nullptr){
44             return false;
45         }
46 
47         if(ra->val == rb->val){
48             return isMirror(ra->left, rb->right) && isMirror(ra->right, rb->left);
49         }else{
50             return false;
51         }
52     }
53 };

 

 posted on 2014-01-01 01:20  zhuli19901106  阅读(202)  评论(0编辑  收藏  举报