1. 程式人生 > >007-100-判斷兩個二叉樹是否相等 Same Tree

007-100-判斷兩個二叉樹是否相等 Same Tree

Question

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

Solution

與二叉樹相關的問題可以用遞迴的思路來解決,對於這個問題,先判斷兩棵樹的當前節點的值是否相等,如果相等,再判斷兩棵樹的左子樹、右子樹分別是否相等,當左右子樹都相等時(邏輯和關係),可以判斷兩棵樹相等。還要考慮空樹的情況,也就是空指標的情況。程式碼如下。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
bool isSameTree(struct TreeNode* p, struct TreeNode* q) {
    if
(p == NULL || q == NULL){ return (p == q); }else{ if(p->val != q->val){ return false; }else{ return isSameTree(p->left, q->left)&&isSameTree(p->right, q->right); } } }

當用以比較的兩個指標都為空時,則認為兩個都是空數,即系相等;當其一為空,另一不為空時,可以判斷兩棵樹不相等。