数据结构_二叉树遍历
package zz; import java.util.ArrayList; import java.util.List; import java.util.Scanner; class TreeNode { int value; TreeNode leftChild; TreeNode rightChild; public TreeNode(int value, TreeNode lc, TreeNode rc) { this.value = value; this.leftChild = lc; this.rightChild = rc; } } public class TreeDemo { //求数的深度 public int getTreeHeight(TreeNode root) { if(root == null) return 0; if(root.leftChild == null && root.rightChild == null) return 1; return 1 + Math.max(getTreeHeight(root.leftChild), getTreeHeight(root.rightChild)); } //递归先序遍历 public void recPreOrder(TreeNode root) { if(root == null) return; System.out.print(root.value + " "); if(root.leftChild != null) recPreOrder(root.leftChild); if(root.rightChild != null) recPreOrder(root.rightChild); } //递归中序遍历 public void recInOrder(TreeNode root) { if(root == null) return; if(root.leftChild != null) recInOrder(root.leftChild); System.out.print(root.value + " "); if(root.rightChild != null) recInOrder(root.rightChild); } //递归后序遍历 public void recPostOrder(TreeNode root) { if(root == null) return; if(root.leftChild != null) recPostOrder(root.leftChild); if(root.rightChild != null) { recPostOrder(root.rightChild); } System.out.print(root.value + " "); } }