Github
public class 二叉树深度 {
public static void main(String[] args) {
TreeNode treeNode1 = new TreeNode(1);
TreeNode treeNode2 = new TreeNode(2);
TreeNode treeNode3 = new TreeNode(3);
TreeNode treeNode4 = new TreeNode(4);
TreeNode treeNode5 = new TreeNode(5);
TreeNode treeNode6 = new TreeNode(6);
treeNode1.left = treeNode2;
treeNode1.right = treeNode3;
treeNode2.left = treeNode4;
treeNode2.right = treeNode5;
treeNode3.left = treeNode6;
System.out.println("args = [" + getHeight(treeNode1) + "]");
}
public static int getHeight(TreeNode root) {
if (root == null) {
return 0;
}
//获取左子树深度
int leftHeight = getHeight(root.getLeft());
//获取右子数深度
int rightHeight = getHeight(root.getRight());
//比较返回最大的
return leftHeight > rightHeight ? leftHeight + 1 : rightHeight + 1;
}
public static class TreeNode {
int val;
TreeNode left;
TreeNode right;
public TreeNode(int val) {
this.val = val;
}
public TreeNode getLeft() {
return left;
}
public void setLeft(TreeNode left) {
this.left = left;
}
public TreeNode getRight() {
return right;
}
public void setRight(TreeNode right) {
this.right = right;
}
}
}
网友评论