给定两个树,判断两个数是否相同 Solution1: DFS (Code will be neat and simple) code 1classSolution {2publicbooleanisSameTree(TreeNode p, TreeNode q) {3if(p ==null&& q ==null)returntrue;4if(p ==null|| q ==null)returnfalse;56if(p.val ==q.val){7returnisSameTree(p.left, q.left...
* TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * };*/classSolution {public:boolisSameTree(TreeNode *p, TreeNode *q) {if(!p && !q)returntrue;elseif(!p &&q)returnfalse;elseif(p && !q)returnfalse;else{if(p->val != q->val)returnfalse;elseret...
没调试,直接提交AC,也算是对自己的一点点肯定和自信吧!??? struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; bool isSameTree(TreeNode *p, TreeNode *q) { //边界条件 if ((p == NULL && q) || (q == NULL...
*/classSolution{public:boolisSameTree(TreeNode*p,TreeNode*q){if(p==NULL&&q==NULL)returntrue;if(p==NULL&&q!=NULL||p!=NULL&&q==NULL)returnfalse;if(p->val!=q->val)returnfalse;returnisSameTree(p->left,q->left)&&isSameTree(p->right,q->right);}};或:/** * Definition for binary...
/*** Definition for a binary tree node.* struct TreeNode {* int val;* TreeNode *left;* TreeNode *right;* TreeNode(int x) : val(x), left(NULL), right(NULL) {}* };*/classSolution{public:boolisSameTree(TreeNode*p,TreeNode*q){if(!p&&!q){returntrue;}elseif(p&&q){return(p...
(来源:https://leetcode.com/problems/same-tree/) 递归 class Solution { public boolean isSameTree(TreeNode p, TreeNode q) { if(p==null || q==null) { return p==q; } if(p.val != q.val) { return false; } return isSameTree(p.left, q.left) && isSameTree(p.right, q.right...
leetcode-100. Same Tree · Tree + DFS + Queue 题面 对比两棵二叉树是否相同,返回结果。 思路 1. 递归解决DFS 首先判断根节点,如果都空,返回true; 如果一空一不空,返回false; 如果都不空,判断两节点值是否相同,若不同,返回false,若相同,递归左子树、右子树...
100. 相同的树 - 给你两棵二叉树的根节点 p 和 q ,编写一个函数来检验这两棵树是否相同。 如果两个树在结构上相同,并且节点具有相同的值,则认为它们是相同的。 示例 1: [https://assets.leetcode.com/uploads/2020/12/20/ex1.jpg] 输入:p = [1,2,3], q = [1,2,
Solution2:前序遍历对比 思路:除了前序的元素值,前序的结构也需要check,是否同为Null或同存在,通过push后(非null) check stack_p.size() != stack_q.size() Time Complexity: O(N) Space Complexity: O(N) Solution1 Code: classSolution1{publicbooleanisSameTree(TreeNode p,TreeNode q){if(p==null...
[find-elements-in-a-contaminated-binary-tree](../../problems/find-elements-in-a-contaminated-binary-tree) | [在受污染的二叉树中查找元素](../../problems/find-elements-in-a-contaminated-binary-tree/README.md) | [cpp](../../problems/find-elements-in-a-contaminated-binary-tree/SOLUTION....