递归实现二叉树遍历以及求最大深度

来源:互联网 发布:2017天天采集软件 编辑:程序博客网 时间:2024/05/17 21:56
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));    }}
阅读全文
1 0
原创粉丝点击