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

二叉树学习笔记。

时间:2014-07-09 21:16:15      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   os   div   new   

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 }

在递归的时候一定要判断下一个递归值是否合法。如果不合法应该怎么办?

二叉树学习笔记。,布布扣,bubuko.com

二叉树学习笔记。

标签:style   blog   color   os   div   new   

原文地址:http://www.cnblogs.com/seansong/p/3829972.html

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