日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

Same Tree

發布時間:2025/4/16 25 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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.

Subscribe?to see which companies asked this question

遞歸方法:

/*** 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)return false;else if(p!=NULL && q==NULL)return false;else{if(p->val != q->val)return false;elsereturn 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) {//非遞歸的方法,主要判斷各個元素是不是相同,就是三種遍歷方法,因為從上到下進行遍歷,最好是層次遍歷queue<TreeNode*> a1;queue<TreeNode*> a2;if(p==NULL && q==NULL) return true;if((p && !q)||(!p && q)||(p->val!=q->val)) return false;a1.push(p);a2.push(q);while(!a1.empty() && !a2.empty()){TreeNode* p1=a1.front();a1.pop();TreeNode* p2=a2.front();a2.pop();//一個重要的是NULL左右子樹也得放進去 保持同步,如果是NULL,則他的左右子樹不用放進去if(p1==nullptr && p2==nullptr) continue; if(p1==nullptr || p2==nullptr) return false; if( p1->val != p2->val) return false; a1.push(p1->left); a1.push(p1->right); a2.push(p2->left); a2.push(p2->right); }return true;} };

總結

以上是生活随笔為你收集整理的Same Tree的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。