当前位置:网站首页>[leetcode refers to the substructure of offer 26. Tree (medium)]

[leetcode refers to the substructure of offer 26. Tree (medium)]

2022-04-23 21:20:00 Minaldo7

subject :

Input two binary trees A and B, Judge B Is it right? A Substructure of .( A convention empty tree is not a substructure of any tree )

B yes A Substructure of , namely A There are emergence and B Same structure and node values .

for example :
Given tree A:
 Insert picture description here
Given tree B:
 Insert picture description here
return true, because B And A A subtree of has the same structure and node values .

 Insert picture description here

source : Power button (LeetCode)
link :https://leetcode-cn.com/problems/shu-de-zi-jie-gou-lcof
Copyright belongs to the network . For commercial reprint, please contact the official authority , Non-commercial reprint please indicate the source .

The problem solving process :

My method ( recursive )

/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */
class Solution {
    
    public static boolean equals(TreeNode A,TreeNode B){
    
		if(A==null&&B==null)  
			return true;
		if(A==null)return false;
        if(B==null)return true;
		return A.val==B.val && equals(A.left, B.left) && equals(A.right, B.right);
	}

    public boolean isSubStructure(TreeNode A, TreeNode B) {
    
        if(A==null || B == null)return false;
		if(equals(A, B))return true;
		return isSubStructure(A.left, B) || isSubStructure(A.right, B);
    }
}

Execution results :

 Insert picture description here

版权声明
本文为[Minaldo7]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/111/202204210544479693.html