考察点
树的遍历
知识点
题目
分析
本题目要求二叉树的深度,遇到树的题目思维肯定要往递归的方向上靠,假如左子树的深度和右子树的深度都求出来了,如何求根结点的深度?肯定是左右子树深度最大值+1,那么这道题目的算法也就出来了
public class Node{
int val;
Node leftChild;
Node rightChild;
public Node(int data) {
this.val = data;
this.leftChild = null;
this.rightChild = null;
}
}
public class BinaryTree {
Node root;
public BinaryTree() {
this.root = null;
}
public void insertTree(int val) {
if (this.root == null) {
Node root = new Node(val);
this.root = root;
} else {
insertChildTree(this.root,val);
}
}
public void insertChildTree(Node node,int val) {
if (node != null && val <= node.val) {
if (node.leftChild == null) {
node.leftChild = new Node(val);
} else {
insertChildTree(node.leftChild,val);
}
}
if (node != null && val > node.val) {
if (node.rightChild == null) {
node.rightChild = new Node(val);
} else {
insertChildTree(node.rightChild,val);
}
}
}
public Node getRoot() {
return this.root;
}
public int getDeep(Node node) {
if(node == null) {
return 0;
}
int left = getDeep(node.leftChild);
int right = getDeep(node.rightChild);
return left > right ? left+1:right+1;
}
}
public class ThirtyNine {
public static void main(String[] args) {
BinaryTree binaryTree = new BinaryTree();
binaryTree.insertTree(7);
binaryTree.insertTree(3);
binaryTree.insertTree(8);
binaryTree.insertTree(1);
binaryTree.insertTree(5);
binaryTree.insertTree(4);
System.out.println(binaryTree.getDeep(binaryTree.getRoot()));
}
}