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.
ExampleExample 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 Given a binary tree, find the largest subtree which is a Binary SearchTree (B...
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 ...
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...
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...
摘要:二叉樹邊界題意高頻題,必須熟練掌握。逆時針打印二叉樹邊界。解題思路根據觀察,我們發現當為左邊界時,也是左邊界當為左邊界時,為空,則也可以左邊界。先加入左邊,加入,然后得到兩個子樹加入,最后加入右邊界。 LeetCode 545. Boundary of Binary Tree 二叉樹邊界Given a binary tree, return the values of its boun...
閱讀 720·2023-04-25 20:32
閱讀 2267·2021-11-24 10:27
閱讀 4520·2021-09-29 09:47
閱讀 2241·2021-09-28 09:36
閱讀 3633·2021-09-22 15:27
閱讀 2756·2019-08-30 15:54
閱讀 370·2019-08-30 11:06
閱讀 1271·2019-08-30 10:58