Same Tree
2015-07-28 13:07
246 查看
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.
Analyse: Compare all nodes in the same place.
1. Recursion
Runtime: 0ms.
2. Iteration with stack used
Runtime: 0ms.
3. Iteration with queue used
Runtime: 4ms.
Two binary trees are considered equal if they are structurally identical and the nodes have the same value.
Analyse: Compare all nodes in the same place.
1. Recursion
Runtime: 0ms.
/** * 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 isSameTree(TreeNode* p, TreeNode* q) { if(!p && !q) return true; if(!p || !q) return false; //the first line eliminated the situation s.t. both trees are null return p->val == q->val && isSameTree(p->left, q->left) && isSameTree(p->right, q->right); } };
2. Iteration with stack used
Runtime: 0ms.
/** * 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 isSameTree(TreeNode* p, TreeNode* q) { stack<TreeNode* > stk; stk.push(p); stk.push(q); while(!stk.empty()){ p = stk.top(); stk.pop(); q = stk.top(); stk.pop(); if(!p && !q) continue; if(!p || !q) return false; if(p->val != q->val) return false; stk.push(p->left); stk.push(q->left); stk.push(p->right); stk.push(q->right); } return true; } };
3. Iteration with queue used
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 isSameTree(TreeNode* p, TreeNode* q) { queue<TreeNode* > qu; qu.push(p); qu.push(q); while(!qu.empty()){ p = qu.front(); qu.pop(); q = qu.front(); qu.pop(); if(!p && !q) continue; if(!p || !q) return false; if(p->val != q->val) return false; qu.push(p->left); qu.push(q->left); qu.push(p->right); qu.push(q->right); } return true; } };
相关文章推荐
- 晶振旁的电阻(并联与串联)
- Tornado.web.Application的settings参数
- 文章标题黑马程序员--C语言的基础知识
- 技术点
- 那些没有root权限的岁月:一分钟解决mutt No mailbox
- tcpcopy 实现( php + python)
- HDU 2023 求平均成绩
- 快排与堆排序、归并排序的比较
- 分布式数据库的未来工坊(1)
- 分布式数据库的未来工坊(2)
- 在 Linux 中安装 Google 环聊桌面客户端
- 大白话讲解卡方鉴定【案例】播放的背景音乐对于卖酒有什么样的销售影响?
- 面向对象的思想概述
- Linux ftp 使用
- linux安全登录之sudo命令
- Android开源框架Universal-Image-Loader详解
- Scala界面GUI编程
- morphia基本API方法
- easyui的datebox最简单的方法来格式化
- Navicat Premium 11.0.16破解注册版