首页 > 代码库 > 二叉树学习笔记。
二叉树学习笔记。
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 } else37 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 } else44 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 @Override53 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 }
在递归的时候一定要判断下一个递归值是否合法。如果不合法应该怎么办?
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。