1. 程式人生 > >【LeetCode & 劍指offer刷題】樹題8:26 樹的子結構(572. Subtree of Another Tree)

【LeetCode & 劍指offer刷題】樹題8:26 樹的子結構(572. Subtree of Another Tree)

【LeetCode & 劍指offer 刷題筆記】目錄(持續更新中...)

572. Subtree of Another Tree

Given two non-empty binary trees   s   and   t , check whether tree   t   has exactly the same structure and node values with a subtree of   s
. A subtree of  s is a tree consists of a node in s  and all of this node's descendants. The tree   s could also be considered as a subtree of itself. Example 1: Given tree s:   3  / \  4  5
/ \ 1 2 Given tree t:  4 / \ 1  2 Return  true , because t has the same structure and node values with a subtree of s. Example 2: Given tree s:      3
    / \    4   5   / \  1  2     /    0 Given tree t:  4 / \ 1 2 Return  false .
  /**  * Definition for a binary tree node.  * struct TreeNode {  *     int val;  *     TreeNode *left;  *     TreeNode *right;  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}  * };  */ /* 問題:判斷某子樹是否是主樹的子結構 方法:前序遍歷的遞迴方法 主樹s, 子樹t */ class Solution { public :     bool isSubtree ( TreeNode * s , TreeNode * t ) //遍歷主樹s(前序遍歷遞迴法)     {         if(s == nullptr) return false ; //前序遍歷遞迴的出口, 注意一定要加判斷空指標的語句,後面有s->left和s->right                 //前序遍歷(遞迴法)主樹t各結點,從根結點到左子樹再到右子樹(s一直在延伸,展開分支)         if ( isSame ( s , t ))  //判斷當前結點下的子樹是否一樣             return true ;          else              //判斷當前結點的左子樹是否為子樹t,再判斷右子樹是否為子樹t             return isSubtree ( s -> left , t ) || isSubtree ( s -> right , t );      } private :     bool isSame ( TreeNode * s , TreeNode * t ) //確定s父結點後,開始同時掃描(遞迴法)s和t,看是各個結點是否相等     {         if ( s == nullptr && t == nullptr ) return true ; //如果最後均遍歷到空結點,返回true         else if ( s == nullptr || t == nullptr ) return false ; //如果一個遍歷到空,一個沒有,說明不同,返回false                 if ( s->val == t->val )         {             return isSame(s->left, t->left) && isSame(s->right, t->right);         }         else             return false ; //不相同,返回假      } };   28 對稱二叉樹(101. Symmetric Tree)