随笔- 509  文章- 0  评论- 151  阅读- 22万 

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   zhuli19901106  阅读(202)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示