LeetCode | Same Tree
来源:互联网 发布:linux中man的用法 编辑:程序博客网 时间:2024/06/10 17:08
题目:
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.
思路:
树的问题大部分都是递归求解。代码:
递归实现:
/** * Definition for binary tree * 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 && p->val == q->val){ return isSameTree(p->left, q->left) && isSameTree(p->right, q->right); } else{ return false; } }};
非递归实现:
/** * Definition for binary tree * 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*> node1; queue<TreeNode*> node2; if(p == NULL && q == NULL){ return true; } else if(p != NULL && q != NULL && p->val == q->val){ node1.push(p); node2.push(q); while(!node1.empty() && !node2.empty()){ TreeNode* n1 = node1.front(); node1.pop(); TreeNode* n2 = node2.front(); node2.pop(); if(n1->left != NULL && n2->left != NULL && n1->left->val == n2->left->val){ node1.push(n1->left); node2.push(n2->left); } else if(!(n1->left == NULL && n2->left == NULL)) { return false; } if(n1->right != NULL && n2->right != NULL && n1->right->val == n2->right->val){ node1.push(n1->right); node2.push(n2->right); } else if(!(n1->right == NULL && n2->right == NULL)) { return false; } } } else{ return false; } return true; }};
- 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
- 2013华为校园招聘上机题 C++ 练习
- kobject和kset .
- 主项定理Master Method
- 自定义注解过滤JUnit测试类
- 总线设备模型-kobject .
- LeetCode | Same Tree
- android_1
- ifstream文件尾最后一行读两次
- 在编译内核的最后阶段出现sdhci_esdhc_imx_pdata未定义的错误
- linux系统编译C++程序时头文件和库文件搜索路径
- 输入四个点的坐标,求证四个点是不是一个矩形
- mips64高精度时钟引起ktime_get时间不准,导致饿狗故障原因分析
- Codeforce 338 C. Divisor Tree(爆搜,3级)
- 九度1008最短路