java两种方法实现(递归与非递归)
树的子结构
http://www.nowcoder.com/questionTerminal/6e196c44c7004d15b1610b9afca8bd88
首先:判断结构相同必须需要的函数
public boolean isSame(TreeNode root1,TreeNode root2){
if(root2 == null) return true;
if(root1 == null) return false;
return root1.val == root2.val
&& isSame(root1.left, root2.left)
&& isSame(root1.right, root2.right);
}
第一种:递归判断 利用好短路特性 20ms
public boolean fun1(TreeNode root1, TreeNode root2) {
if(root1 == null || root2 == null) return false;
return isSame(root1, root2) || isSame(root1.left, root2) || isSame(root1.right,root2);
}
第二:非递归实现:广度优先遍历判断 14ms
public boolean fun2(TreeNode root1, TreeNode root2) {
if(root1 == null || root2 == null){
return false;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root1);
while(!queue.isEmpty()){
TreeNode cur = queue.poll();
if(isSame(cur, root2)) return true;
else{
if(cur.left != null) queue.offer(cur.left);
if(cur.right != null) queue.offer(cur.right);
}
}
return false;
}
vivo公司福利 364人发布