To prove safety Offer - face questions substructure 26. Tree (double recursion)

1. Topic

Two binary inputs A and B, B is not determined substructure A's. (Not arbitrary convention empty tree structure of one sub-tree)

B is a sub-structure A, i.e., A has the same structure and appearance and Node B values.

例如:
给定的树 A:

     3
    / \
   4   5
  / \
 1   2
给定的树 B:

   4 
  /
 1
返回 true,因为 B 与 A 的一个子树拥有相同的结构和节点值。

示例 1:
输入:A = [1,2,3], B = [3,1]
输出:false

示例 2:
输入:A = [3,4,5,1,2], B = [4,1]
输出:true

限制:
0 <= 节点个数 <= 10000

Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/shu-de-zi-jie-gou-lcof
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.

2. Problem Solving

  • A traversing each node, and the root value equal to B, open check again recursively
class Solution {
	bool found = false;
public:
    bool isSubStructure(TreeNode* A, TreeNode* B) {
        if(!A || !B) return false;
        if(A->val == B->val)
        {
        	found = check(A, B);
        	if(found)
        		return found;
        }
        isSubStructure(A->left,B);
        isSubStructure(A->right,B);
        return found;
    }

    bool check(TreeNode* A, TreeNode* B)
    {
    	if(found || !B || !A)
    	{
    		if(found || !B)
    			return true;
    		return false;
    	}
    	if(A->val == B->val)
    	{
    		return (check(A->left,B->left)&&check(A->right,B->right));
    	}
    	return false;
    }
};

Here Insert Picture Description


  • Optimization: return isSubStructure(A->left,B)||isSubStructure(A->right,B)can pruning, timely return after finding
class Solution {
	bool found = false;
public:
    bool isSubStructure(TreeNode* A, TreeNode* B) {
        if(!A || !B) return false;
        if(A->val == B->val)
        {
        	found = check(A, B);
        	if(found)
        		return found;
        }   
        return isSubStructure(A->left,B)||isSubStructure(A->right,B);
    }

    bool check(TreeNode* A, TreeNode* B)
    {
    	if(found || !B || !A)
    	{
    		if(found || !B)
    			return true;
    		return false;
    	}
    	if(A->val == B->val)
    	{
    		return (check(A->left,B->left)&&check(A->right,B->right));
    	}
    	return false;
    }
};

Here Insert Picture Description

Published 700 original articles · won praise 649 · Views 200,000 +

Guess you like

Origin blog.csdn.net/qq_21201267/article/details/104710978