1. 程式人生 > >sameTree用深度優先搜尋判斷兩棵樹是否相同 #演算法#

sameTree用深度優先搜尋判斷兩棵樹是否相同 #演算法#

Given two binary trees, write a function to check if they are the same or not. 給定兩個二叉樹,寫一個函式檢查它們是否相同。 Two binary trees are considered the same if they are structurally identical and the nodes have the same value. 若兩個二叉樹的結構相同且節點有相同值,則它們相同。

·Example 1:

Input:     1         1
          / \       / \
         2   3     2   3

        [1,2,3],   [1,2,3]

Output: true

·Example 2:

Input:     1         1
          /           \
         2             2

        [1,2],     [1,null,2]

Output: false

·Example 3:

Input:     1         1
          / \       / \
         2   1     1   2

        [1,2,1],   [1,1,2]

Output: false

思路

只需要一個前序遍歷(深度優先),每次判斷分三種情況: (1)if (p != NULL && q != NULL) 兩個根節點都不為空,則判斷值是否相等,若值相等,則判斷其左右子樹是否都相等; (2)else if (p != NULL || q != NULL) 兩個根節點只有一個不為空,則肯定不相等,return false; (3)else 兩個根節點都為空,則相等。 判斷子樹是否相等可以用遞迴的方法進行。

程式碼

class Solution {
public:
    bool isSameTree(TreeNode* p, TreeNode* q) {
        if
(p != NULL && q != NULL){ if(p->val != q -> val) return false; return isSameTree(p->left, q->left) && isSameTree(p->right, q->right); } else if(p != NULL || q != NULL) return false; return true; } };