我之前学数据结构的时候对树相关的知识似懂非懂,直到现在才有勇气来一个一个克服相关的常见操作。
除了树相关的操作还学到了一个类。参考的两篇博客,分别是 传送门① 和 传送门②
二叉树的深度
思路:可以递归查找,当节点为空时返回0,然后分别求出左右节点孩子的深度,求最大值返回(根节点的深度还要加上)
import java.util.ArrayDeque;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
public class TreeDepth {
public static void main(String[] args) {
int[] arr = {1,2,3,4,5,6,7,8};
Node root = createBinRree(arr);
int depth = binTreeDepth(root);
System.out.println(depth);
}
private static int binTreeDepth(Node root) {
if(root == null)
return 0;
int left = binTreeDepth(root.lchild);
int right = binTreeDepth(root.rchild);
return 1 + Math.max(left, right);
}
private static Node createBinRree(int[] arr) {
List<Node> list = new LinkedList<Node>();
int len = arr.length;
for(int i=0; i<len; i++) {
list.add(new Node(arr[i]));
}
for(int i=0; i<len/2-1; i++) {
list.get(i).lchild = list.get(i*2 + 1);
list.get(i).rchild = list.get(i*2 + 2);
}
int lastIndex = len/2-1;
list.get(lastIndex).lchild = list.get(lastIndex*2+1);
if(len%2 == 1)
list.get(lastIndex).rchild = list.get(lastIndex*2+2);
return list.get(0);
}
static class Node{
private int data;
private Node lchild;
private Node rchild;
public Node(int data) {
super();
this.data = data;
this.lchild = null;
this.rchild = null;
}
}
}
二叉树的宽度
思路:按层次遍历,每次得到的宽度求最大值(宽度就是二叉树横向最长节点数)。
可以利用队列,根节点存入队列。然后在队列不为空的情况下,每次得到当前的最大宽度,然后把队列里(上次存入的)所有节点出队,并存入当前节点的左右孩子。
import java.util.ArrayDeque;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
public class TreeDepth {
public static void main(String[] args) {
int[] arr = {1,2,3,4,5,6,7,8};
Node root = createBinRree(arr);
int width = binTreeWidth(root);
System.out.println(width);
}
private static int binTreeWidth(Node root) {
if(root == null)
return 0;
Queue<Node> q = new ArrayDeque<Node>();
q.add(root);
int width = 1;
while(!q.isEmpty()) {
int size = q.size();
width = Math.max(size, width);
while(size > 0) {
size --;
Node node = q.poll();
if(node.lchild != null)
q.add(node.lchild);
if(node.rchild != null)
q.add(node.rchild);
}
}
return width;
}
private static Node createBinRree(int[] arr) {
List<Node> list = new LinkedList<Node>();
int len = arr.length;
for(int i=0; i<len; i++) {
list.add(new Node(arr[i]));
}
for(int i=0; i<len/2-1; i++) {
list.get(i).lchild = list.get(i*2 + 1);
list.get(i).rchild = list.get(i*2 + 2);
}
int lastIndex = len/2-1;
list.get(lastIndex).lchild = list.get(lastIndex*2+1);
if(len%2==1)
list.get(lastIndex).rchild = list.get(lastIndex*2+2);
return list.get(0);
}
static class Node{
private int data;
private Node lchild;
private Node rchild;
public Node(int data) {
super();
this.data = data;
this.lchild = null;
this.rchild = null;
}
}
}
如有错误或不合理的地方,敬请指正~
加油!!