class BinaryTreeNode {
BinaryTreeNode left;
BinaryTreeNode right;
int val;
BinaryTreeNode(int val) {
this.val = val;
}
}
public class Test{
//求二叉树的深度
static int getDepth(BinaryTreeNode root){
if(root==null){
return 0;
}
int left=getDepth(root.left);
int right=getDepth(root.right);
return left>right?left+1:right+1;
}
static void scanNodes(BinaryTreeNode root){
if(root==null){
return;
}
System.out.println(root.val); //先序遍历
scanNodes(root.left);
//System.out.println(root.val); 中序遍历
scanNodes(root.right);
//System.out.println(root.val); 后序遍历
}
public static void main(String[] args)
{
BinaryTreeNode root=new TreeNode(1);
BinaryTreeNode left1=new TreeNode(2);
BinaryTreeNode left2=new TreeNode(3);
BinaryTreeNode right1=new TreeNode(4);
BinaryTreeNode right2=new TreeNode(5);
//创建一棵树
root.left=left1;
left1.right=left2;
root.right=right1;
right1.right=right2;
scanNodes(root);
System.out.println("树的深度是:"+getDepth(root));
}
}
递归实现二叉树遍历以及求最大深度
最新推荐文章于 2024-07-31 15:54:23 发布