节点的dat是
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
//使用层次遍历来创建二叉树
public TreeNode createBinaryTreeByLevel(Integer[] array) {
if (array.length == 0) {
return null;
}
TreeNode root = new TreeNode(array[0]);
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.offer(root);
int i = 1;
Integer temp = null;
while (i < array.length) {
TreeNode node = queue.poll();
temp = array[i++];
if(temp != null){
TreeNode left = new TreeNode(temp);
node.left = left;
queue.offer(left);
}
temp = array[i++];
if(temp != null){
TreeNode right = new TreeNode(temp);
node.right = right;
queue.offer(right);
}
}
return root;
}
/**
* 使用递归来创建二叉树
*/
public TreeNode createBinaryTreeByRecursive(int[] array, int index) {
TreeNode tn = null;
if (index < array.length) {
int value = array[index];
tn = new TreeNode(value);
tn.left = createBinaryTreeByRecursive(array, index * 2 + 1);
tn.right = createBinaryTreeByRecursive(array, index * 2 + 2);
return tn;
}
return tn;
}
/**
* 不使用递归来创建二叉树
*/
public TreeNode createBinaryTree(int[] array) {
List<TreeNode> nodeList = new LinkedList<TreeNode>();
for (int i = 0; i < array.length; i++) {
nodeList.add(new TreeNode(array[io]));
}
for (int parentIndex = 0; parentIndex < array.length / 2 - 1; parentIndex++) {
nodeList.get(parentIndex).left = nodeList.get(parentIndex * 2 + 1);
nodeList.get(parentIndex).right = nodeList.get(parentIndex * 2 + 2);
}
int lastParentIndex = array.length / 2 - 1;
nodeList.get(lastparentIndex).left = nodeList.get(lastparentIndex * 2 + 1);
if (lastParentIndex % 2 == 1) {
nodeList.get(lastparentIndex).left = nodeList.get(lastparentIndex * 2 + 2);
}
return nodeList.get(0);
}
/*判断两棵树是否完全相同*/
//其实就是同时遍历两棵树,判断每个节点是否相同
public boolean isSameTree(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 isSameTree(p.left, q.left)&& isSameTree(p.right, q.right);
}
/*判断是否为对称二叉树*/
// 也是同时遍历两棵树,只是比对节点的顺序不一样
public boolean isSymmetric(TreeNode root) {
return isMirror(root, root);
}
/**
*
* @param t1
* @param t2
* @return
*/
public boolean isMirror(TreeNode t1,TreeNode t2){
if(t1 == null && t2 == null){
return true;
}
if(t1==null || t2 == null){
return false;
}
return (t1.val == t2.val)&& isMirror(t1.left, t2.right) && isMirror(t1.right, t2.left);
}
//一个树的最大深度
public int maxDepth(TreeNode root) {
if(root == null){
return 0;
}
int left = maxDepth(root.left);
int right = maxDepth(root.right);
return left>right?left+1:right+1;
}
//一个树的最小深度
public int minDepth(TreeNode root) {
if (root == null) {
return 0;
}
if (root.left == null && root.right == null)
return 1;
int min = Integer.MAX_VALUE;
if (root.left != null) {
min = Math.min(minDepth(root.left), min);
}
if (root.right != null) {
min = Math.min(minDepth(root.right), min);
}
return min+1;
}