LeetCode(100)题解--Same Tree
2015-10-08 22:23
423 查看
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.
思路: DFS
AC代码:
1.递归
2.非递归
题目:
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.
思路: DFS
AC代码:
1.递归
/** * 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==NULL && q==NULL) return true; else if(p!=NULL&&q!=NULL){ bool ju; if(p->val==q->val) ju=true; else return false; if (p->left==NULL && q->left==NULL) ; else if(p->left!=NULL && q->left!=NULL) ju=ju&&isSameTree(p->left,q->left); else return false; if (p->right==NULL && q->right==NULL) ; else if(p->right!=NULL && q->right!=NULL) ju=ju&&isSameTree(p->right,q->right); else return false; return ju; } else return false; } };
2.非递归
/** * 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==NULL&&q==NULL) return true; else if(p!=NULL && q!=NULL){ stack<TreeNode*> ms1,ms2; ms1.push(p); ms2.push(q); TreeNode* p1,*q1; while(!ms1.empty()){ p1=ms1.top(); q1=ms2.top(); if(p1->val!=q1->val) return false; else{ ms1.pop(); ms2.pop(); if(p1->right==NULL&&q1->right==NULL) ; else if(p1->right!=NULL&&q1->right!=NULL){ ms1.push(p1->right); ms2.push(q1->right); } else return false; if(p1->left==NULL&&q1->left==NULL) ; else if(p1->left!=NULL&&q1->left!=NULL){ ms1.push(p1->left); ms2.push(q1->left); } else return false; } } return true; } else return false; } };
相关文章推荐
- GPU share memory 的应用 (主要内容转载)
- *第六周*数据结构实践项目一【建立顺序栈算法库】
- C++中typename和class的区别
- kernel版本更新追踪
- sprintf的强大功用
- swift版的StringAttribute
- Android中触摸事件传递分发机制
- Hadoop之HDFS---浅谈DN、NN、SNN
- java 学习日记---------简易学生信息管理系统
- 屏幕坐标和世界坐标的转换+对象池技术(3D打地鼠小游戏)
- NYOJ 358 取石子(五)(斐波那契博弈)
- objective_c
- 数据结构Java 线性表与顺序表
- JNI中的string返回jstring
- 电脑史话(1)
- UI设计师产品构思过程中需要有一个系统思维方向
- ef之 entitystate状态
- 图像处理函数详解——imfilter
- 电脑史话(2)
- 51nod 1004 n^n的末位数字