572. Another tree subtree

subtree-of-another-tree

Title Description

Given two binary nonempty s and t, and the test is included in s t subtrees having the same structure and the node values. s of a subtree including all the descendants of a node and the node s. s can be seen as its own subtree.

Example 1:
given tree s:
1
given tree t:
2
returns true, because t s, with a sub-tree nodes have the same structure and values.

Example 2:
given tree s:
3
given tree T:
4
returns false.

Code

public class Solution {
	
	public boolean isSubtree(TreeNode s,TreeNode t){
		/*
		 * equals方法检查以s和t为根的两棵子树是否相等
		 * isSubtree递归检查t是否存在于s的左或右子树中;
		 * 又或者以s为根的这棵树就是与以t为根的那棵树相等的树,使用equals检查即可。
		 */
		if(s == null && t!=null){
			//递归进行到s为空,返回false
			return false;
		}
		
		boolean isSubInLeft = isSubtree(s.left,t);
		boolean isSub = equals(s,t);//检查当前结点s是否可以和子树t匹配
		boolean isSubInRight = isSubtree(s.right,t);
		if(isSubInLeft || isSub || isSubInRight){
			return true;
		}
		return false;
	}
	
	public boolean equals(TreeNode s,TreeNode t){
		if(s == null && t == null){
			//比较到最下部
			return true;
		}else if(s == null || t == null){
			//两者中只有一者为空,必然不等,处理t是s“子树中的一部分”,即示例2的情况
			return false;
		}
		if(s.val == t.val){
			boolean resOfLeft =  equals(s.left,t.left);
			boolean resOfRight = equals(s.right,t.right);
			if(resOfLeft && resOfRight){
				//两孩子结点相等
				return true;
			}
		}
		//除以上情况外的其它情况,返回false
		return false;
	}
}

Performance
Performance

Published 75 original articles · won praise 0 · Views 1500

Guess you like

Origin blog.csdn.net/qq_34087914/article/details/104159075