1. 层序构建和先序遍历:
1 public class Tree { 2 public Tree left; 3 public Tree right; 4 public int val; 5 6 public Tree() { 7 8 } 9 10 public Tree(String n) { 11 this.val = Integer.parseInt(n); 12 } 13 14 public Tree createTreeByLevel(String[] var) { 15 if (var == null) { 16 return null; 17 } 18 if (var[0] == "#") { 19 return null; 20 } 21 int length = var.length; 22 Tree root = new Tree(var[0]); 23 Tree cur = root; 24 int count = 1; 25 insertByLevelOrder(cur, length, count, var); 26 27 return root; 28 } 29 30 void insertByLevelOrder(Tree cur, int length, int count, String[] var) { 31 if (count * 2 - 1 >= length) { 32 return; 33 } 34 if (var[count * 2 - 1] != "#") { 35 cur.left = new Tree(var[count * 2 - 1]); 36 } else 37 cur.left = null; 38 if (count * 2 >= length) { 39 return; 40 } 41 if (var[count * 2] != "#") { 42 cur.right = new Tree(var[count * 2]); 43 } else 44 cur.right = null; 45 if (cur.left != null) 46 insertByLevelOrder(cur.left, length, count * 2, var); 47 if (cur.right != null) 48 insertByLevelOrder(cur.right, length, count * 2 + 1, var); 49 // return cur; 50 } 51 52 @Override 53 public String toString() { 54 String result = ""; 55 result = result + this.val + " "; 56 Tree t = this; 57 if (t.left != null) { 58 59 result += t.left.toString(); 60 } 61 if (t.right != null) { 62 result += t.right.toString(); 63 } 64 return result; 65 } 66 }
在递归的时候一定要判断下一个递归值是否合法。如果不合法应该怎么办?
二叉树学习笔记。
时间: 2024-11-18 15:50:59