LeetCode OJ 之 Same Tree (相同樹的判斷)
阿新 • • 發佈:2019-02-04
題目:
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; if(p == NULL || q == NULL)//剪枝 return false; if(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) { stack<TreeNode*> s;//把q,q的結點成對入棧,再成對出棧進行比較 s.push(p); s.push(q); while(!s.empty()) { p = s.top(); //取出棧頂 s.pop(); //刪除棧頂 q = s.top(); s.pop(); if (!p && !q) //p,q都為空,繼續遍歷,出棧判斷 continue; if (!p || !q) //p,q只有一個為空,則返回假 return false; if (p->val != q->val) //p,q不等,返回假 return false; s.push(p->left); s.push(q->left); s.push(p->right); s.push(q->right); } return true; } };