[LeetCode]: 100: Same Tree
2015-09-03 08:55
239 查看
题目:
Given two binary trees, write a function to check if they are equal or not.
Two binary trees are considered equal if they are structurally identical and the nodes have the same value.
解析:
比较两个二叉树是否相同采用将二叉树进行“先序遍历”,“中序遍历”和“后序遍历”,如果其中有两种遍历的结果相同,则这两个二叉树相等
代码:
网上高人的代码如下:添加了空树的判断
Given two binary trees, write a function to check if they are equal or not.
Two binary trees are considered equal if they are structurally identical and the nodes have the same value.
解析:
比较两个二叉树是否相同采用将二叉树进行“先序遍历”,“中序遍历”和“后序遍历”,如果其中有两种遍历的结果相同,则这两个二叉树相等
代码:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public boolean isSameTree(TreeNode p, TreeNode q) { String ResultL1 = Front(p); String ResultL2 = Front(q); String ResultL3 = Middle(p); String ResultL4 = Middle(q); /* String ResultL5 = Last(p); String ResultL6 = Last(q); */ if(ResultL1.equals(ResultL2) && ResultL3.equals(ResultL4)){ return true; } else{ return false; } } public static String Front(TreeNode Tree){ if(Tree == null){ return "X"; } String strResult = ""; strResult += Tree.val; strResult += Front(Tree.left); strResult += Front(Tree.right); return strResult; } public static String Middle(TreeNode Tree){ if(Tree == null){ return "X"; } String strResult = ""; strResult += Middle(Tree.left); strResult += Tree.val; strResult += Middle(Tree.right); return strResult; } public static String Last(TreeNode Tree){ if(Tree == null){ return "X"; } String strResult = ""; strResult += Last(Tree.left); strResult += Last(Tree.right); strResult += Tree.val; return strResult; } }
网上高人的代码如下:添加了空树的判断
bool isSameTree(TreeNode *p, TreeNode *q) { // Start typing your C/C++ solution below // DO NOT write int main() function if (p == NULL && q == NULL) return true; else if (p == NULL || q == NULL) return false; return p->val == q->val && isSameTree(p->left, q->left) && isSameTree(p->right, q->right); }
相关文章推荐
- 关于windows保护模式的一些个人见解
- POJ 3370 && HDU 1808 Halloween treats(鸽巢原理)
- POJ 2356 Find a multiple(鸽巢原理)
- POJ 2142 && HDU 1356 The Balance(一元线性同余方程)
- POJ 1730 Perfect Pth Powers(数论)
- POJ 2407 Relatives(欧拉函数)
- POJ 2505 && HDU 1517 A multiplication game(博弈论)
- NOIP 2010 乌龟棋 DP (COGS 519)
- Kafka深度解析
- POJ 2975 Nim(博弈论)
- POJ 2234 Matches Game(博弈论)
- 面试之线程篇
- Linux网络管理工具总结
- 7.1Android服务绑定
- TQ2440 学习笔记—— 15、基础知识小结【汇编、vi】
- sqlite3使用
- expdp\impdp及exp\imp
- php大力力 [044节] PHP的POST语句一定要大写!!if(!empty($_POST['id'])) {
- HDOJ 5424 Rikka with Graph II 暴力dfs
- android 内存管理