Home > Back-end >  For bosses to help me take a look at the difficult problem of binary tree
For bosses to help me take a look at the difficult problem of binary tree

Time:11-22

Given two non-empty binary tree s and t, does it include in test s and t have the same structure and node values subtree, s a tall tree including s, all the children of a node and the node s can also be a KeZi trees as its own,

Example 1:
Given the tree s:

3
/\
4, 5
/\
1
2A given tree t:

4
/\
1
2Returns true, because the t and s of a tall tree to have the same structure and node values,

Example 2:
Given the tree s:

3
/\
4, 5
/\
1
2
0
A given tree t:

4
/\
1
2Returns false,

The code is as follows:
Struct TreeNode {
int val;
Struct TreeNode * left;
Struct TreeNode * right;
};

Bool isequal (struct TreeNode * s, struct TreeNode * t) {
if (! S & amp; & ! T) return true;
The return (s & amp; & T & amp; & S - & gt; Val==t - & gt; Val & amp; & Isequal (s - & gt; Left, t - & gt; Left) & amp; & Isequal (s - & gt; Right, t - & gt; Right));
}

Bool isSubtree (struct TreeNode * s, struct TreeNode * t) {
if (! S) return false.// this line of code: why can't I delete?
Return (isequal (s, t) | | isSubtree (s - & gt; Left, t) | | isSubtree (s - & gt; Right, t));
}

CodePudding user response:

if (! S) return false.==this judgment sample 2 is the case,,

CodePudding user response:

IsSubtree (s - & gt; Left, t)//recursive no judgment here s - & gt; Is left null (null is possible), so will do judgment within isSubtree
IsSubtree (s - & gt; Right, t)//in the same way, and so here
If change to
Return isequal (s, t) | | (s - & gt; Left & amp; & IsSubtree (s - & gt; Left, t)) | | (s - & gt; Right & amp; & IsSubtree (s - & gt; Right, t))
So isSubtree function do not need to judge the
But, from the point of the design of function, the judge s inside isSubtree function is reasonable, because the user calls isSubtree, not necessarily to determine whether a parameter is null, so try to inside function can ensure fault-tolerant application does not collapse,

  • Related