【递归】子树
题目要求
有两个不同大小的二叉树: T1有上百万的节点; T2有好几百的节点。请设计一种算法,判定T2是否为T1的子树。
思路解析
若根节点相同,则直接返回true。
若根节点不同,则递归比较T1的左、右子树和T2。
要注意的点
- isEqual()函数的实现。
- 对于T1、T2是空值情况的具体判断。
Java实现
/** * Definition of TreeNode: * public class TreeNode { * public int val; * public TreeNode left, right; * public TreeNode(int val) { * this.val = val; * this.left = this.right = null; * } * } */ public class Solution { /** * @param T1: The roots of binary tree T1. * @param T2: The roots of binary tree T2. * @return: True if T2 is a subtree of T1, or false. */ public boolean isEqual(TreeNode T1, TreeNode T2) { if(T1 == null || T2 == null) { return T1 == T2; } if(T1.val != T2.val) { return false; } return isEqual(T1.left, T2.left) && isEqual(T1.right, T2.right); } public boolean isSubtree(TreeNode T1, TreeNode T2) { if(T2 == null) return true; if(T1 == null) return false; if(isEqual(T1, T2)) return true; if(isSubtree(T1.left, T2) || isSubtree(T1.right, T2)) return true; return false; } }
相关推荐
steeven 2020-11-10
Tips 2020-10-14
nongfusanquan0 2020-08-18
yedaoxiaodi 2020-07-26
清溪算法君老号 2020-06-27
pengkingli 2020-06-25
yishujixiaoxiao 2020-06-25
清溪算法 2020-06-21
RememberMePlease 2020-06-17
nurvnurv 2020-06-05
wonner 2020-06-04
SystemArchitect 2020-06-02
码墨 2020-05-29
清溪算法 2020-05-27
choupiaoyi 2020-05-27
清溪算法 2020-05-25
bluewelkin 2020-05-19