package demo;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
public class BalanceTree {
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
/**
* 平衡二叉树
* @param root
* @return
*/
public boolean isBalanced(TreeNode root) {
return depth(root) != -1;
}
private int depth(TreeNode root) {
if (root == null){
return 0;
}
int left = depth(root.left);
if(left == -1) {
return -1;
}
int right = depth(root.right);
if(right == -1) {
return -1;
}
return Math.abs(left - right) < 2 ? Math.max(left, right) + 1 : -1;
}
/**
* 二叉树最大深度
* @param root
* @return
*/
public int maxDepth(TreeNode root) {
if (null == root){
return 0;
}
int leftDepth = maxDepth(root.left);
int rightDepth = maxDepth(root.right);
return Math.max(leftDepth,rightDepth)+1;
}
//二叉树最小深度
public int minDepth(TreeNode root) {
if (null == root){
return 0;
}
int leftDepth = minDepth(root.left);
int rightDepth = minDepth(root.right);
if (0 != leftDepth && 0 != rightDepth){
return Math.min(leftDepth,rightDepth)+1;
}
return Math.max(leftDepth,rightDepth)+1;
}
/**
* 层次变量二叉树
* @param root
* @return
*/
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> resultList=new LinkedList<>();
if (null == root){
return resultList;
}
LinkedList<TreeNode> nodeQueue = new LinkedList<>();
nodeQueue.add(root);
while (!nodeQueue.isEmpty()){
int currentLevel = nodeQueue.size();
List<Integer> currentNodeList = new LinkedList<>();
while (currentLevel>0){
currentLevel--;
TreeNode currentNode = nodeQueue.poll();
if (null == currentNode){
continue;
}
currentNodeList.add(currentNode.val);
if (null != currentNode.left){
nodeQueue.add(currentNode.left);
}
if (null != currentNode.right){
nodeQueue.add(currentNode.right);
}
}
resultList.add(currentNodeList);
}
return resultList;
}
/**
* 递归求二叉树左视图
* @param root
* @return
*/
public void treeLeftView(TreeNode root,List<Integer> leftViewNodeList,int currentLevel) {
//List<Integer> leftViewNodeList=new LinkedList<>();
if (null == root){
return ;
}
if (currentLevel == leftViewNodeList.size()){
leftViewNodeList.add(root.val);
}
treeLeftView(root.left,leftViewNodeList,currentLevel++);
treeLeftView(root.right,leftViewNodeList,currentLevel++);
}
/**
* 递归求二叉树右视图
* @param root
* @return
*/
public void treeRightView(TreeNode root,List<Integer> leftViewNodeList,int currentLevel) {
//List<Integer> leftViewNodeList=new LinkedList<>();
if (null == root){
return ;
}
if (currentLevel == leftViewNodeList.size()){
leftViewNodeList.add(root.val);
}
treeLeftView(root.right,leftViewNodeList,currentLevel++);
treeLeftView(root.left,leftViewNodeList,currentLevel++);
}
/**
* 求视图并打印
* @param root
*/
public void leftView(TreeNode root){
if (null == root){
return;
}
List<Integer> leftViewNodeList = new LinkedList<>();
int currentLevel = 0;
treeLeftView(root,leftViewNodeList,currentLevel);
//打印
leftViewNodeList.forEach((node)-> System.out.println(node));
}
}