LeetCode演算法題101:對稱二叉樹解析
阿新 • • 發佈:2018-12-19
給定一個二叉樹,檢查它是否是映象對稱的。 例如,二叉樹 [1,2,2,3,4,4,3] 是對稱的。
1
/ \
2 2
/ \ / \
3 4 4 3
但是下面這個 [1,2,2,null,3,null,3] 則不是映象對稱的:
1
/ \
2 2
\ \
3 3
說明: 如果你可以運用遞迴和迭代兩種方法解決這個問題,會很加分。
既然說用兩種方法會很加分那就都得會啊,(樹結構還是很陌生,程式碼參考了答案)首先是遞迴方法,從根節點來開始考慮,首先根節點一定是相同的,然後左子節點要等於右子節點,然後再往下考慮一步,左子節點的左子節點要等於右子節點的右子節點,而且左子節點的右子節點要等於右子節點的左子節點。然後依次往下推,從一開始就比較的是樹的左側和右側的值。 C++原始碼:
/**
* 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 isSymmetric(TreeNode* root) {
return isMirror(root, root);
}
bool isMirror(TreeNode* p, TreeNode* q)
{
if(p==NULL&&q==NULL) return true;
if(p==NULL||q==NULL) return false;
return (p->val==q->val&&isMirror(p->left,q->right)&&isMirror(p->right, q->left));
}
};
python3原始碼:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isSymmetric(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
return self.isMirror(root, root)
def isMirror(self, p, q):
if p==None and q==None:
return True
if p==None or q==None:
return False
return p.val==q.val and self.isMirror(p.left, q.right) and self.isMirror(q.left, p.right)
然後說一下迭代,我覺得迭代和遞迴其實差不多,這裡用了佇列來儲存子節點,每次存一對,左子節點的左子節點和右子節點的右子節點或者左子節點的右子節點和右子節點的左子節點。然後迭代比較這兩個點的值。這裡產生了一個疑惑,遞迴用的是棧的原理,而佇列其實就是個堆,為什麼產生了一樣的效果呢?我覺得應該是這樣,這裡的遞迴其實並沒有用到後面的值,在遞迴的過程中其實隨時可能中斷遞迴,也就是遞迴的目的是為了遍歷整個樹,所以和使用佇列直接遍歷整個樹沒什麼區別。關於迭代方法的思想我覺得其實就是把這個樹都按對裝到了佇列中,然後進行比較,只是程式碼中在放的過程中進行比較並且將比較過後的刪除並給出結果。這個結果是假,那麼直接退出,如果是真,繼續遍歷。 C++原始碼:
/**
* 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 isSymmetric(TreeNode* root) {
queue<TreeNode*> q;
q.push(root);
q.push(root);
while(!q.empty())
{
TreeNode* a = q.front();
q.pop();
TreeNode* b = q.front();
q.pop();
if(a==NULL&&b==NULL) continue;
if(a==NULL||b==NULL) return false;
if(a->val!=b->val) return false;
q.push(a->left);
q.push(b->right);
q.push(a->right);
q.push(b->left);
}
return true;
}
};
python3原始碼:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isSymmetric(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
q = [root]
q.append(root)
while len(q)!=0:
a = q.pop(0)
b = q.pop(0)
if a==None and b==None:
continue
if a==None or b==None:
return False
if a.val != b.val:
return False
q.append(a.left)
q.append(b.right)
q.append(b.left)
q.append(a.right)
return True