1.树的子结构
题目描述
输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构)
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public boolean HasSubtree(TreeNode root1,TreeNode root2) {
//1.遍历树A,查找是否有相等结点 2.判断从这个结点开始下面的结点是否相等
boolean result = false;
if (root1 != null && root2 != null) {
if (root1.val == root2.val) {
result = IfSubEquals(root1, root2);
}
if (!result) {
result = HasSubtree(root1.left, root2);
}
if (!result) {
result = HasSubtree(root1.right, root2);
}
}
return result;
}
private static boolean IfSubEquals(TreeNode root1, TreeNode root2) {
if (root2 == null) {
return true;
}
if (root1 == null) {
return false;
}
if (root1.val != root2.val) {
return false;
}
return IfSubEquals(root1.left, root2.left) &&
IfSubEquals(root1.right, root2.right);
}
}
2.二叉树的镜像
题目描述
操作给定的二叉树,将其变换为源二叉树的镜像。
输入描述:
二叉树的镜像定义:源二叉树
8
/
6 10
/ \ /
5 7 9 11
镜像二叉树
8
/
10 6
/ \ /
11 9 7 5
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public void Mirror(TreeNode root) {
// 1.交换根的左右子树 2.交换非叶子结点的左右子树
if (root == null) {
return;
}
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
if (root.left != null) {
Mirror(root.left);
}
if (root.right != null) {
Mirror(root.right);
}
}
}
对递归体的过程不是很清楚:只要不是叶子结点,就进行递归交换左右子树。