Subtree of Another Tree - LintCode

描述
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.

思路
對於t和s判斷t是否等於s,是的話返回true,否則返回t左右子樹和s是否相等的並。

#ifndef C1165_H
#define C1165_H
#include<iostream>
using namespace std;
class TreeNode{
public:
    int val;
    TreeNode *left, *right;
    TreeNode(int val){
        this->val = val;
        this->left = this->right = NULL;
    }
};
class Solution {
public:
    /**
    * @param s: the s' root
    * @param t: the t' root
    * @return: whether tree t has exactly the same structure and node values with a subtree of s
    */
    bool isSubtree(TreeNode * s, TreeNode * t) {
        // Write your code here
        //若s和t不完全相同,繼續判斷s的左右子樹和t,返回結果的並
        if (!s&&!t)
            return true;
        else if (!s || !t)
            return false;
        if (isEqual(s, t))
            return true;
        else
            return isSubtree(s->left, t) || isSubtree(s->right, t);
    }
    //判斷root和node是否完全相同
    bool isEqual(TreeNode *root, TreeNode *node)
    {
        if (!root&&!node)
            return true;
        else if (!root || !node)
            return false;
        if (root->val == node->val)
        {
            return isEqual(root->left, node->left) && isEqual(root->right, node->right);
        }
        else
            return false;
    }
};
#endif
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章