LeetCode -- Symmetric Tree
2015-12-01 09:43
381 查看
题目描述:
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
判断一个树的左右子树是否完全相等。
思路:分别对左右子树进行中序遍历,然后对遍历结果进行一一对比。
实现代码:
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
判断一个树的左右子树是否完全相等。
思路:分别对左右子树进行中序遍历,然后对遍历结果进行一一对比。
实现代码:
public class Solution { public bool IsSymmetric(TreeNode root) { if(root == null || root.left ==null && root.right == null){ return true; } var left = new List<string>(); var right = new List<string>(); TravelL(root.left, left); TravelR(root.right, right); if(left.Count != right.Count){ return false; } for(var i = 0;i < left.Count; i++){ if(left[i] != right[i]){ return false; } } return true; } public void TravelL(TreeNode node , IList<string> result){ if(node == null){ result.Add("N"); return; } result.Add(node.val.ToString()); TravelL(node.left, result); TravelL(node.right, result); } public void TravelR(TreeNode node , IList<string> result){ if(node == null){ result.Add("N"); return; } result.Add(node.val.ToString()); TravelR(node.right, result); TravelR(node.left, result); } }
相关文章推荐
- Android 获取手机系统的声音设置管理通知提醒的声音
- Failed to load JavaHL Library问题
- 获取当前时间的年、月、日、时、分、秒
- CLRS 10.3指针和对象的实现
- Java学习日记-2.4 浮点数
- WEB端IIS服务器开发常识之HTTP状态码
- Xcode插件之Alcatraz的安装和遇到的问题
- html、css
- Oriented Object Proposals
- h.264转flv converter
- android 程序退出的对话框
- iOS 解决xib加载UITableViewCell的宽度不适应问题
- java中成员变量与局部变量区别分析
- 使用dwz-ria Jquery ui框架出现“HierarchyRequestError: Node cannot be inserted at the specified point in th
- Sencha Extjs4.2 皮肤制作
- LeetCode -- Subsets
- 线程与进程的概念、使用
- 详解JavaScript函数
- 华为oj之兄弟单词
- Codeigniter Helper辅助函数