[程序员代码面试指南]二叉树问题-判断t1树是否包含t2树的全部拓扑结构、[LeetCode]572. 另一个树的子树

题目1 解

  • 先序遍历树1,判断树1以每个节点为根的子树是否包含树2的拓扑结构。
  • 时间复杂度:O(M*N)
  • 注意区分判断总体包含关系、和判断子树是否包含树2的函数。

代码

public class Main {
	public static void main(String args[]) {
		//test
                Node n1=new Node(1);
		Node n2=new Node(2);
		Node n3=new Node(3);
		Node n4=new Node(4);
		n1.left=n2;
		n1.right=n3;
		n3.left=n4;
		
		Node n5=new Node(3);
		Node n6=new Node(4);
		n5.left=n6;
		
		if(contains(n1,n5)) {
			System.out.print("contains");
		}
		else {
			System.out.print("not contains");
		}
	}
	
	public static boolean contains(Node root,Node rootTest) {
		if(rootTest==null) {
			return true;
		}
		if(root==null) {
			return false;
		}
		return check(root,rootTest)||contains(root.left,rootTest)||contains(root.right,rootTest);
	}
	
	public static boolean check(Node root,Node rootTest) {
		if(rootTest==null) {
			return true;
		}
		if(root==null||root.val!=rootTest.val) {
			return false;
		}
		return check(root.left,rootTest.left)&&check(root.right,rootTest.right);                                              
	}
}

题目2 572. 另一个树的子树

给定两个非空二叉树 s 和 t,检验 s 中是否包含和 t 具有相同结构和节点值的子树。s 的一个子树包括 s 的一个节点和这个节点的所有子孙。s 也可以看做它自身的一棵子树。

示例 1:
给定的树 s:

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

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

示例 2:
给定的树 s:

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

   4
  / \
 1   2
返回 false。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/subtree-of-another-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题解

题意和上题稍有不同,包含的树必须无多余的叶子结点,具体见例子2。
仍然使用递归。分别判断subTree和SameTree。

代码

class Solution {
    public boolean isSubtree(TreeNode s, TreeNode t) {
        if(s==null&&t==null){
            return true;
        }
        if(s==null||t==null){
            return false;
        }
        return isSameTree(s,t)||isSubtree(s.left,t)||isSubtree(s.right,t);
    }

    public boolean isSameTree(TreeNode t1,TreeNode t2){
        if(t2==null&&t1==null){//
            return true;
        }
        if(t1==null||t2==null){//
            return false;
        }
        return t1.val==t2.val&&isSameTree(t1.left,t2.left)&&isSameTree(t1.right,t2.right);
    }
}

posted on 2019-06-13 00:20  coding_gaga  阅读(265)  评论(0编辑  收藏  举报

导航