[剑指offer]判断两个二叉树是否相等及变形
剑指offer 26,27,28 这三道题代码结构相似,可以放在一起练习。
剑指offer 28 对称的二叉树
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public boolean isSymmetric(TreeNode root) { if(root == null) return true; return dfs(root.left, root.right); } public boolean dfs(TreeNode p, TreeNode q){ if(p == null && q == null) return true; if(p == null || q == null) return false; if(p.val != q.val) return false; return dfs(p.left, q.right) && dfs(p.right, q.left); } }
剑指offer 27 二叉树的镜像
class Solution { public TreeNode mirrorTree(TreeNode root) { if(root == null) return null; TreeNode temp = root.left; root.left = root.right; root.right = temp; mirrorTree(root.left); mirrorTree(root.right); return root; } }
剑指offer 26 树的子结构
class Solution { public boolean isSubStructure(TreeNode A, TreeNode B) { if(A == null || B == null) return false; if(dfs(A, B)){ return true; } return isSubStructure(A.left, B) || isSubStructure(A.right, B); } public boolean dfs(TreeNode p, TreeNode q){ if(q == null) return true; if(p == null || p.val != q.val) return false; return dfs(p.left, q.left) && dfs(p.right, q.right); } }