1. 程式人生 > >【一天一道LeetCode】#100. Same Tree(100題大關)

【一天一道LeetCode】#100. Same Tree(100題大關)

一天一道LeetCode

本系列文章已全部上傳至我的github,地址:ZeeCoder‘s Github
歡迎大家關注我的新浪微博,我的新浪微博
歡迎轉載,轉載請註明出處

(一)題目

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 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) { stack<pair<TreeNode*,TreeNode*>> TwoTreeNode;//用棧實現非遞迴 TwoTreeNode.push(make_pair<TreeNode*,TreeNode*>((TreeNode*)p,(TreeNode*)q));//初始化 while(!TwoTreeNode.empty()) { auto temp = TwoTreeNode.top();//去除棧頂
TwoTreeNode.pop();//處理當前節點 TreeNode* ptemp = temp.first; TreeNode* qtemp = temp.second; if(ptemp==NULL&&qtemp==NULL) continue;//兩個都為空 else if(ptemp!=NULL&&qtemp!=NULL){//兩個都不為空 if(ptemp->val==qtemp->val)//判斷值是否相等 { TwoTreeNode.push(make_pair(ptemp->left,qtemp->left));//相等則放入棧等待處理 TwoTreeNode.push(make_pair(ptemp->right,qtemp->right)); } else return false;//不相等返回false } else return false;//一個為空另一個不為空直接返回false } return true;//全部處理完都相等就返回true } };