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) {//非遞歸的方法,主要判斷各個元素是不是相同,就是三種遍歷方法,因為從上到下進行遍歷,最好是層次遍歷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;} };
總結
- 上一篇: Rotate List
- 下一篇: Maximum Depth of Bin