Symmetric Tree
2015-07-28 13:29
417 查看
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree is symmetric:
But the following is not:
Note:
Bonus points if you could solve it both recursively and iteratively.
confused what
Analyse: the same as Same Tree
1. Recursion
Runtime: 8ms.
2. Iteration
Runtime: 4ms.
For example, this binary tree is symmetric:
1 / \ 2 2 / \ / \ 3 4 4 3
But the following is not:
1 / \ 2 2 \ \ 3 3
Note:
Bonus points if you could solve it both recursively and iteratively.
confused what
"{1,#,2,3}"means? > read more on how binary tree is serialized on OJ.
Analyse: the same as Same Tree
1. Recursion
Runtime: 8ms.
/** * 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) return true; return symmetric(root->left, root->right); } bool symmetric(TreeNode* leftNode, TreeNode* rightNode){ if(!leftNode && !rightNode) return true; if(!leftNode || !rightNode) return false; return leftNode->val == rightNode->val && symmetric(leftNode->left, rightNode->right) && symmetric(leftNode->right, rightNode->left); } };
2. Iteration
Runtime: 4ms.
/** * 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) return true; stack<TreeNode* > stk; stk.push(root->left); stk.push(root->right); while(!stk.empty()){ TreeNode* node1 = stk.top(); stk.pop(); TreeNode* node2 = stk.top(); stk.pop(); if(!node1 && !node2) continue; if(!node1 || !node2) return false; if(node1->val != node2->val) return false; stk.push(node1->left); stk.push(node2->right); stk.push(node1->right); stk.push(node2->left); } return true; } };
相关文章推荐
- 写在受洗之前:我为什么成为基督徒
- 线程启动代码
- 部署ntp服务器笔记与时区的介绍与修改
- Delphi操作XML
- UIActionSheet 控件
- ogre接入cegui
- Tomcat 简介之【目录结构】
- 多线程学习笔记一---------------------多线程前奏
- 05SkypeForBusiness2015--Lync2010升级到2013迁移CMS
- gclub ทางออกเรื่องเงินที่ดีที่สุด
- Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[UITableView
- mysql 命令行脚本导入导出
- 阿里常考面试题及答案
- ios开发—利用xcode tabbed模块快速开发标签栏应用
- 网络编程系列之三 信号量
- Session 缓存
- Cordys HTML5 SDK BootStrap
- 提取合适连通区域轮廓
- 一款好玩的软件
- iOS 数据请求 GZip数据压缩和解压缩问题