is subtree or not

2024-01-04 12:08
文章标签 subtree

本文主要是介绍is subtree or not,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

判断一个树是不是另一个树的子树

boolean issametree(TreeNode root1, TreeNode root2) {if (root1 == null && root2 == null)return true;if (root1 != null && root2 != null) {return root1.val == root2.val && issametree(root1.left, root2.left)&& issametree(root1.right, root2.right);}return false;}public boolean issubtree(TreeNode big, TreeNode small) {if (big != null && small != null) {if (big.val == small.val) {if (issametree(big, small))return true;}else {if (big.left != null && issubtree(big.left, small)) {return true;}if (big.right != null && issubtree(big.right, small)) {return true;}}}return false;}public static void main(String[] args) {SameTreeSubTree s = new SameTreeSubTree();TreeNode tn1 = new TreeNode(1);TreeNode tn2 = new TreeNode(2);TreeNode tn3 = new TreeNode(3);TreeNode tn4 = new TreeNode(4);TreeNode tn5 = new TreeNode(5);tn1.left = tn2;tn1.right = tn3;tn4.left = tn5;System.out.println(s.issubtree(tn1, tn2));System.out.println(s.issubtree(tn1, tn4));}


这篇关于is subtree or not的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/569282

相关文章

245.Subtree-子树(容易题)

子树 题目 有两个不同大小的二进制树: T1 有上百万的节点; T2 有好几百的节点。请设计一种算法,判定 T2 是否为 T1的子树。 注意事项 若 T1 中存在从节点 n 开始的子树与 T2 相同,我们称 T2 是 T1 的子树。也就是说,如果在 T1 节点 n 处将树砍断,砍断的部分将与 T2 完全相同。样例 下面的例子中 T2 是 T1 的子树: 下面的例子中 T2 不是 T1

get (tree node val - (subtree val sum))

给一个tree,返回每个点左右子树的和与自己值的差,用递归做,还问了不递归怎么做 package tree;import java.util.*;import z_dataStructure.TreeNode;public class TreeNodeMinusSubtreeSum {public static void main(String[] args) {TreeNode root

Subtree with Maximum Average

Given a binary tree, find the subtree with maximum average. Return the root of the subtree. python:一定要注意,除法的精度问题。leetcode中不一定使用的是python3.X """Definition of TreeNode:class TreeNode:def __init__(s

[leetcode]2265. Count Nodes Equal to Average of Subtree

问题入口 时间复杂度:O(n),空间复杂度:O(h) class Solution {public:int count = 0;pair<int, int> postOder(TreeNode* root){if (!root)return {0, 0};pair<int, int> left = postOder(root->left);pair<int, int> right = pos

21 结点之和最小的子树(Minimum Subtree)

文章目录 1 题目2 解决方案2.1 思路2.2 时间复杂度2.3 空间复杂度 3 源码3.1 遍历法 1 题目 题目:结点之和最小的子树(Minimum Subtree) 描述:给一棵二叉树, 找到和为最小的子树, 返回其根节点。输入输出数据范围都在int内。 lintcode题号——596,难度——easy 样例1: 输入:{1,-5,2,1,2,-4,-5}