leetcode第五題 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

 

這個題目利用深度搜索去做,因爲只要發現有一個分支不對稱,那麼就可以判斷這兩個二叉樹不相同

#include <iostream>
using namespace std;
//////鏈表的節點創建,創建一個節點/////////
struct TreeNode {
       int val;
       TreeNode *lp;
       TreeNode *rp;
       TreeNode();
       TreeNode(int a){val=a;lp=NULL;rp=NULL;};   ////這裏創建一個結構體的構造函數,很方便,初始化的時候直接進行初始化
     };

bool isSameTree(TreeNode* p, TreeNode* q) {
    if (p == NULL && q == NULL) return true;  ////當搜索到最底層的時候,返回true
    if (p == NULL || q == NULL) return false;
    if (p->val != q->val) return false;  /////
    return isSameTree(p->lp, q->lp) && isSameTree(p->rp, q->rp); ///這種情況實際上是p和q的val相同的情況,那麼就繼續比較他們的左右子樹,
}

int main() {
    TreeNode *a = new TreeNode(1);
    TreeNode *b = new TreeNode(2);
    TreeNode *c = new TreeNode(3);
    TreeNode *d = new TreeNode(4);
    TreeNode *e = new TreeNode(5);
    TreeNode *f = new TreeNode(6);

    TreeNode *a1 = new TreeNode(1);
    TreeNode *b1 = new TreeNode(2);
    TreeNode *c1= new TreeNode(3);
    TreeNode *d1 = new TreeNode(4);
    TreeNode *e1 = new TreeNode(5);
    TreeNode *f1 = new TreeNode(6);

    a->lp = b;
    a->rp = c;
    b->lp = d;
    b->rp = e;
    c->lp = f;

    a1->lp = b1;
    a1->rp = c1;
    b1->lp = d1;
//    b1->rp = e1;
    c1->lp = f1;
    isSameTree(a,a1);


    return 0;
}

這裏我做的二叉樹是這樣的:

 

 

輸入兩個二叉樹:

    1          1
   / \        / \
  2   3      2   3

  /      \      /         /      /

4       5   6       4      6   

通過debug發現,一次搜索的順序是1,2,4,5 然後就結束了,

說明當 return A&&B的時候,只要確認A是false,那麼就沒必要再計算B了,但是如果A是true的話,此時無法確認返回值,則需要繼續計算B,正是因爲語言有這樣的功能,才正真實現了,深度搜索。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章