国产xxxx99真实实拍_久久不雅视频_高清韩国a级特黄毛片_嗯老师别我我受不了了小说

資訊專欄INFORMATION COLUMN

[LeetCode] Subtree of Another Tree

greatwhole / 1504人閱讀

Problem

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

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.

Solution
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isSubtree(TreeNode s, TreeNode t) {
        if (t == null) return true;
        if (s == null) return t == null;
        if (isSametree(s, t)) return true;
        return isSubtree(s.left, t) || isSubtree(s.right, t);
    }
    private boolean isSametree(TreeNode s, TreeNode t) {
        if (s == null) return t == null;
        if (t == null) return s == null;
        if (s.val != t.val) return false;
        return isSametree(s.left, t.left) && isSametree(s.right, t.right);
    }
}

文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。

轉載請注明本文地址:http://specialneedsforspecialkids.com/yun/69361.html

相關文章

  • LeetCode[333] Largest BST Subtree

    摘要:復雜度思路考慮對于每一個節點來說,能組成的的。那么并且所以我們需要兩個返回值,一個是這個是不是,另一個是當前的能組成的最大的值。代碼這個能構成一個這個不能構成一個 LeetCode[333] Largest BST Subtree Given a binary tree, find the largest subtree which is a Binary SearchTree (B...

    WrBug 評論0 收藏0
  • [LeetCode] Largest BST Subtree

    Largest BST Subtree Given a binary tree, find the largest subtree which is a Binary Search Tree (BST), where largest means subtree with largest number of nodes in it. Note: A subtree must include all ...

    Youngdze 評論0 收藏0
  • [LintCode/LeetCode] Binary Tree Pruning

    Problem Binary Tree PruningWe are given the head node root of a binary tree, where additionally every nodes value is either a 0 or a 1. Return the same tree where every subtree (of the given tree) not...

    rockswang 評論0 收藏0
  • [LeetCode] 545. Boundary of Binary Tree

    Problem Given a binary tree, return the values of its boundary in anti-clockwise direction starting from root. Boundary includes left boundary, leaves, and right boundary in order without duplicate no...

    newtrek 評論0 收藏0
  • LeetCode 545. Boundary of Binary Tree 二叉樹邊界

    摘要:二叉樹邊界題意高頻題,必須熟練掌握。逆時針打印二叉樹邊界。解題思路根據觀察,我們發現當為左邊界時,也是左邊界當為左邊界時,為空,則也可以左邊界。先加入左邊,加入,然后得到兩個子樹加入,最后加入右邊界。 LeetCode 545. Boundary of Binary Tree 二叉樹邊界Given a binary tree, return the values of its boun...

    Astrian 評論0 收藏0

發表評論

0條評論

最新活動
閱讀需要支付1元查看
<