题目:
给定两个非空二叉树 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。
解题思路:
先通过前序遍历寻找和当前节点t相等的点,如果相等,对以这个点为根的树和以t为根的树进行匹配,检查两棵树是否相等。
代码实现:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public boolean isSubtree(TreeNode s, TreeNode t) { if (s == null && t == null) return true; else if (s == null && t != null) return false; else if (s != null && t == null) return true; else { Stack<TreeNode> stack = new Stack<TreeNode>(); while (s != null) { if (s.val == t.val && isEqual(s, t)) return true; if (s.right != null) stack.push(s.right); s = s.left; if (s == null && !stack.isEmpty()) { s = stack.pop(); } } } return false; } private boolean isEqual(TreeNode s, TreeNode t) { if (s == null && t == null) return true; if (s == null && t != null) return false; if (s != null && t == null) return false; if (s.val != t.val) return false; return isEqual(s.left, t.left) && isEqual(s.right, t.right); } }