二叉树结点的定义与先序(中左右)、中序(左中右)、后序(左右中)遍历,顺便写个最大深度,都是递归实现,之后再学习非递归的方法。
先序遍历的结果为: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)); } }