[LeetCode] Same Tree
来源:互联网 发布:货架重量计算软件 编辑:程序博客网 时间:2024/06/09 18:20
前言
Leetcode之blabla Tree系列的一道水题。
题目
https://leetcode.com/problems/same-tree/
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.
分析
仍然是两种基本思路——递归与非递归,递归比较容易理解,而非递归,就是迭代。具体见代码。
代码
Recursive solution, easy to understand.
bool isSameTree(TreeNode* p, TreeNode* q) { if (!p || !q) return q == p;// to judge p and q is both empty tree or not. return p->val == q->val && isSameTree(p->left, q->left) && isSameTree(p->right, q->right);}
Non-recursive solution:
class Solution {public: bool isSameTree(TreeNode* p, TreeNode* q) { stack<TreeNode*> stack_p; stack<TreeNode*> stack_q; if(p) stack_p.push(p);//p is not empty if(q) stack_q.push(q);//q is not empty while(!stack_p.empty() && !stack_q.empty()){ TreeNode* cur_p=stack_p.top(); TreeNode* cur_q=stack_q.top(); stack_p.pop(); stack_q.pop(); if(cur_p->val!=cur_q->val) return false; if(cur_p->left) stack_p.push(cur_p->left);// cur_p->left != NULL if(cur_q->left) stack_q.push(cur_q->left);// cur_q->left != NULL if(stack_p.size() != stack_q.size()) return false; if(cur_p->right) stack_p.push(cur_p->right); if(cur_q->right) stack_q.push(cur_q->right); } return stack_p.size() == stack_q.size(); }};
0 0
- Leetcode - Tree - Same Tree
- [leetcode][tree] Same Tree
- LeetCode: Same Tree
- LeetCode Same Tree
- [Leetcode] Same Tree
- LeetCode : Same Tree
- [LeetCode] Same Tree
- leetcode 65: Same Tree
- Leetcode 100 Same Tree
- [leetcode] Same Tree
- [LeetCode]Same Tree
- [leetcode]Same Tree
- [Leetcode]Same Tree
- Leetcode: Same Tree
- [LeetCode] Same Tree
- LeetCode-Same Tree
- [leetcode] Same Tree
- LeetCode - Same Tree
- Java程序的工作方式
- 利用动态规划将逻辑函数化简到最简形式
- ruby warrior intermediate个人攻略(可能会更新
- POJ 3286 How many 0's?(数位dp)
- js作用域
- [LeetCode] Same Tree
- 第一行代码-10.3 解析XML数据格式
- html设置按钮背景颜色与背景图片一样,即设置按钮背景透明
- bzoj3524【POI2014】Couriers
- 数据与数据结构
- Linux服务器配置-jdk
- Web前端工程师成长之路——知识汇总
- python 简介
- 2016.2.29晚