leetcode 572. Subtree of Another Tree

来源:互联网 发布:linux 每10秒 shell 编辑:程序博客网 时间:2024/06/04 23:27
Given two non-empty binary trees s and t, check whether tree t has exactly the same structure and node values with a subtree of s. A subtree of s is a tree consists of a node in s and all of this node's descendants. The tree s could also be considered as a subtree of itself.Example 1:Given tree s:     3    / \   4   5  / \ 1   2Given tree t:   4   / \ 1   2Return true, because t has the same structure and node values with a subtree of s.Example 2:Given tree s:     3    / \   4   5  / \ 1   2    /   0Given tree t:   4  / \ 1   2Return false.

有两种解法,一种是递归,一种转字符串后匹配。
第一种解法,简单好写,第二种解法可以找到多个位置(如果有的话)

先是递归的解法
递归的是两个树的根的位置
isSame递归的判断是否一致

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public boolean isSubtree(TreeNode s, TreeNode t) {        if (s == null) return false;        if (isSame(s, t)) return true;        return isSubtree(s.left, t) || isSubtree(s.right, t);    }    private boolean isSame(TreeNode s, TreeNode t) {        if (s == null && t == null) return true;        if (s == null || t == null) return false;        if (s.val != t.val) return false;        return isSame(s.left, t.left) && isSame(s.right, t.right);    }}

然后是转化为字符串的解法
由于t匹配无非三种,t匹配s, 匹配s的左子树部分,匹配s的右子树部分,因此在生成序列的时候,采用先序遍历的方式。
需要注意的是,遍历中需要将空的子孩子加入。

public class Solution { public boolean isSubtree(TreeNode s, TreeNode t) {        String spreorder = generatepreorderString(s);         String tpreorder = generatepreorderString(t);        return spreorder.contains(tpreorder) ;    }    public String generatepreorderString(TreeNode s){        StringBuilder sb = new StringBuilder();        Stack<TreeNode> stacktree = new Stack();        stacktree.push(s);        while(!stacktree.isEmpty()){           TreeNode popelem = stacktree.pop();           if(popelem==null)              sb.append(",#"); // Appending # inorder to handle same values but not subtree cases           else                    sb.append(","+popelem.val);           if(popelem!=null){                stacktree.push(popelem.right);                    stacktree.push(popelem.left);             }        }        return sb.toString();    }}
原创粉丝点击