Same Tree
来源:互联网 发布:有淘宝店铺就能贷款吗? 编辑:程序博客网 时间:2024/06/05 15:28
Description:
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.
代码:
#include <iostream>#include <stack>#define Elementype intusing namespace std;typedef struct TreeNode //树结点{ Elementype val; TreeNode *left; TreeNode *right; TreeNode(Elementype x) : val(x), left(nullptr), right(nullptr) {}} *Tree;//全局索引变量int index = 0;//使用先序遍历创建创建二叉树void MakeBinaryTree(Tree &T, Elementype value[]){ Elementype c = value[index++]; if (c == '#') T = nullptr; else { T = new TreeNode(c); MakeBinaryTree(T->left, value); MakeBinaryTree(T->right, value); }}bool isSameTree(Tree T1, Tree T2){ stack<Tree> sk; Tree p = nullptr; Tree q = nullptr; sk.push(T1); sk.push(T2); while (!sk.empty()) { p = sk.top(); sk.pop(); q = sk.top(); sk.pop(); if (!p && !q) continue; if (!p || !q) return false; if (p->val != q->val) return false; sk.push(p->left); sk.push(q->left); sk.push(p->right); sk.push(q->right); } return true;}int main(){ Tree T1 = nullptr, T2 = nullptr,T3 = nullptr; //注意,每个结点都要有值,注意这里的取值不要等于35,即# Elementype data1[11] = { 3, 9, '#', '#', 20, 15, '#', '#', 7, '#', '#' }; Elementype data2[11] = { 3, 9, '#', '#', 20, 15, '#', '#', 7, '#', '#' }; Elementype data3[11] = { 3, 8, '#', '#', 20, 15, '#', '#', 7, '#', '#' }; MakeBinaryTree(T1, data1); index = 0; MakeBinaryTree(T2, data2); index = 0; MakeBinaryTree(T3, data3); cout <<"T1 == T2 ? "<<boolalpha<<isSameTree(T1,T2) << endl; cout << "T1 == T3 ? " << boolalpha << isSameTree(T1, T3) << endl; system("pause"); return 0;}
测试:
0 0
- Same Tree
- Same Tree
- Same Tree
- Same Tree
- Same Tree
- Same Tree
- Same Tree
- Same Tree
- Same Tree
- Same Tree
- Same tree
- Same Tree
- Same Tree
- Same Tree
- Same Tree
- Same Tree
- Same Tree
- Same Tree
- mysql 性能优化方向
- kmp算法中next[]数组求法的基本思想
- 使用Spring3.2.0+Hibernate3.2.2+Struts2 2.2.3整合小demo以及配置使用的jar包集合
- Spring整合JMS(一)——基于ActiveMQ实现
- C# IQueryable和IEnumerable的区别
- Same Tree
- 我的include和activity的使用
- js 字符串 replace replaceAll
- 7.2 ipu_device.c分析(二)---具体函数分析
- 极光推送使用方法介绍
- win装vim
- oracle 导入数据泵数据库 (表空间创建、授权等)
- 实模式和保护模式区别及寻址方式
- 线程调度四(setDaemon方法的使用)