package xcc.test;
import java.util.LinkedList;
import java.util.Stack;
import xcc.bean.TreeNode;
public class BLTest {
/**
* 分层遍历二叉树(迭代)
* 原理:使用队列实现(先进先出)
*/
public static void levelTraversalIte(TreeNode root) {
if (root == null) {
return;
}
LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
queue.push(root);
while (!queue.isEmpty()) {
TreeNode cur = queue.removeFirst();
System.out.print(cur.val + " ");
if (cur.left != null) {
queue.add(cur.left);
}
if (cur.right != null) {
queue.add(cur.right);
}
}
}
/**
* 将二叉树变为有序的双向链表(迭代)
*/
public static TreeNode convertBST2DLL(TreeNode root) {
if(root == null){
return null;
}
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode cur = root; // 指向当前处理节点
TreeNode old = null; // 指向前一个处理的节点
TreeNode head = null; // 链表头
while( true ){
while(cur != null){ // 先添加一个非空节点所有的左孩子到栈
stack.push(cur);
cur = cur.left;
}
if(stack.isEmpty()){
break;
}
// 因为此时已经没有左孩子了,所以输出栈顶元素
cur = stack.pop();
if(old != null){
old.right = cur;
}
if(head == null){ // /第一个节点为双向链表头节点
head = cur;
}
old = cur; // 更新old
cur = cur.right; // 准备处理右子树
}
return head;
}
/**
* 判断2棵树是否是相同的树
* (1)如果两棵二叉树都为空,返回真
* (2)如果两棵二叉树一棵为空,另一棵不为空,返回假
* (3)如果两棵二叉树都不为空,如果对应的左子树和右子树都同构返回真,其他返回假
*/
public static boolean isSameRec(TreeNode r1, TreeNode r2) {
// 如果两棵二叉树都为空,返回真
if (r1 == null && r2 == null) {
return true;
}
// 如果两棵二叉树一棵为空,另一棵不为空,返回假
else if (r1 == null || r2 == null) {
return false;
}
if(r1.val != r2.val){
return false;
}
boolean leftRes = isSameRec(r1.left, r2.left); // 比较对应左子树
boolean rightRes = isSameRec(r1.right, r2.right); // 比较对应右子树
return leftRes && rightRes;
}
/**
* 判断二叉树是不是平衡二叉树 递归解法:
* (1)如果二叉树为空,返回真
* (2)如果二叉树不为空,如果左子树和右子树都是AVL树并且左子树和右子树高度相差不大于1,返回真,其他返回假
*/
public static int getDepthRec(TreeNode root) {
if (root == null) {
return 0;
}
int left = getDepthRec(root.left);
int right = getDepthRec(root.right);
return Math.max(left, right) + 1;
}
public static boolean isAVLRec(TreeNode root) {
if(root == null){ // 如果二叉树为空,返回真
return true;
}
// 如果左子树和右子树高度相差大于1,则非平衡二叉树, getDepthRec()是前面实现过的求树高度的方法
if(Math.abs(getDepthRec(root.left) - getDepthRec(root.right)) > 1){
return false;
}
// 递归判断左子树和右子树是否为平衡二叉树
return isAVLRec(root.left) && isAVLRec(root.right);
}
public static void main(String[] args) {
/*
1
/ \
2 3
/ \ \
4 5 6
*/
TreeNode r1 = new TreeNode(1);
TreeNode r2 = new TreeNode(2);
TreeNode r3 = new TreeNode(3);
TreeNode r4 = new TreeNode(4);
TreeNode r5 = new TreeNode(5);
TreeNode r6 = new TreeNode(6);
r1.left = r2;
r1.right = r3;
r2.left = r4;
r2.right = r5;
r3.right = r6;
BLTest.convertBST2DLL(r1);
}
}
二叉树判断(相同、分层遍历、平衡二叉树)
最新推荐文章于 2022-08-07 19:55:22 发布