leetcode--Same Tree
来源:互联网 发布:什么是数据审计追踪 编辑:程序博客网 时间:2024/06/06 03:41
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.
思路1:递归,但性能很低
思路2:层次遍历,对每一个对应的节点进行检查是否完全相同(取值,左右子树是否为空等)
class Solution {public: bool isSameTree(TreeNode* p, TreeNode* q) { 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); }};/** * 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; if(!isSameNode(p, q)) return false; queue<TreeNode*> leftq; queue<TreeNode*> rightq; leftq.push(p); rightq.push(q); while(!leftq.empty()&&!rightq.empty()) { TreeNode* lnode=leftq.front(); TreeNode* rnode=rightq.front(); leftq.pop(); rightq.pop(); if(!isSameNode(lnode->left, rnode->left)) return false; if(lnode->left&&rnode->left) { leftq.push(lnode->left); rightq.push(rnode->left); } if(!isSameNode(lnode->right, rnode->right)) return false; if(lnode->right&&rnode->right) { leftq.push(lnode->right); rightq.push(rnode->right); } } return true; } bool isSameNode(TreeNode* p, TreeNode *q) { if(!p && !q) return true; if((p && !q) || (!p && q) || (p->val != q->val)) return false; return true; }};
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
- 拼接三角形
- linux学习笔记之文件权限与目录配置
- leetcode--Search Insert Position
- 3、Java内存模型
- web 服务器 rewrite配置 虚拟域名设置
- leetcode--Same Tree
- Bootstrap实现瀑布流照片显示
- 选择排序—简单选择排序
- 判断树 B 是不是 树 A 的子树
- Java学习之迭代器详解
- Redis集群安装
- ros+matlab
- 为什么使用 Go 语言?
- 策略模式