码迷,mamicode.com
首页 > 其他好文 > 详细

二叉树的遍历

时间:2015-10-07 17:30:30      阅读:131      评论:0      收藏:0      [点我收藏+]

标签:

二叉树结点的定义与先序(中左右)、中序(左中右)、后序(左右中)遍历,顺便写个最大深度,都是递归实现,之后再学习非递归的方法。

 

技术分享

先序遍历的结果为:5,2,4,1,3,8,4,2,9,中序遍历的结果:4,2,1,5,4,8,2,3,9,后序遍历结果:4,1,2,4,2,8,9,3,5。

package leetcode;

class TreeNode
{
    TreeNode left;
    TreeNode right;
    int val;
    TreeNode(int val)
    {
        this.val = val;
    }
    static int getDepth(TreeNode root)
    {
        if(root==null)
        {
            return 0;
        }
        int right = getDepth(root.right);
        int left = getDepth(root.left);
        return left>right?left+1:right+1;
    }
    static void scanNodes(TreeNode 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)
    {
        TreeNode root = new TreeNode(5);
        TreeNode left1 = new TreeNode(2);
        TreeNode left2 = new TreeNode(1);
        TreeNode left3 = new TreeNode(4);
        TreeNode right1 = new TreeNode(3);
        TreeNode right2 = new TreeNode(8);
        TreeNode right3 = new TreeNode(9);
        TreeNode right4 = new TreeNode(4);
        TreeNode right5 = new TreeNode(2);
        root.left = left1;
        left1.right = left2;
        left1.left = left3;
        root.right = right1;
        right1.left = right2;
        right1.right = right3;
        right2.left = right4;
        right2.right = right5;
        scanNodes(root);
        System.out.println("The depth of BinaryTree is: "+getDepth(root));
    }

}

 

二叉树的遍历

标签:

原文地址:http://www.cnblogs.com/hemoely/p/4858965.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!