二叉树的节点结构
//二叉链表表示
private TreeNode leftNode;
private TreeNode rightNode;
int data;
一、创建一个二叉树
//创建一个树 //如果输入有问题转换就有异常产生 public TreeNode CreateTree() { try { Console.WriteLine("===If you input -1 it will be break!"); Console.Write("===Input you data:"); int data = int.Parse(Console.ReadLine()); Console.WriteLine("===----------------------"); if (data == -1) return null; else { TreeNode node = new TreeNode(); node.Data = data; Console.WriteLine("\n===Input {0} left data:", data); node.LeftNode = CreateTree(); Console.WriteLine("\n===Input {0} right data:", data); node.RightNode = CreateTree(); return node; } } catch (Exception) { Console.WriteLine("\n===Yon Input Error! So this node is null!!!"); return null; } }
二、先序遍历递归
public void DLR(TreeNode t) { if(!IsNull(t)){ Console.Write("{0} ",t.Data); DLR(t.LeftNode); DLR(t.RightNode); } }
//非递归实现 public void test1(TreeNode root) { Stack<TreeNode> stack = new Stack<TreeNode>(); TreeNode index=root; while(index!=null||stack.Count>0){ if(index!=null){ Console.Write("{0} ",index.Data); stack.Push(index); index = index.LeftNode; } else { index = stack.Pop(); //stack.Pop(); index = index.RightNode; } } }
三、中序遍历
public void LDR(TreeNode t) { if (!IsNull(t)) { LDR(t.LeftNode); Console.Write("{0} ", t.Data); LDR(t.RightNode); } }
//中序非递归 public void test2(TreeNode root) { Stack<TreeNode> stack = new Stack<TreeNode>(); TreeNode index = root; while (index != null || stack.Count > 0) { if (index != null) { // Console.Write("{0} ", index.Data); stack.Push(index); index = index.LeftNode; } else { index = stack.Pop(); Console.Write("{0} ", index.Data); //stack.Pop(); index = index.RightNode; } } }
四、后序遍历
public void LRD(TreeNode t) { if (!IsNull(t)) { LRD(t.LeftNode); LRD(t.RightNode); Console.Write("{0} ", t.Data); } }
//非递归后序 public void test3(TreeNode root){ Stack<TreeNode> stack = new Stack<TreeNode>(); Stack<int> flag = new Stack<int>(); TreeNode index=root; //index为树木的根了 //然后都入栈 第一次访问的标记为0 ,第二次访问为1 while (index != null || stack.Count > 0) { if (index != null) { stack.Push(index); index = index.LeftNode; flag.Push(0); }else { index = stack.Pop(); int flag_index = flag.Pop(); if (flag_index == 0) { flag.Push(1); stack.Push(index); index = index.RightNode; } else { Console.Write("{0} ",index.Data); index = null; } } } }
五、借助队列按层遍历(广度优先遍历)
public void test4(TreeNode root) { Queue<TreeNode> queue = new Queue<TreeNode>(); queue.Enqueue(root); while(queue.Count>0){ TreeNode t = queue.Dequeue(); Console.Write(t.Data+" "); if (t.LeftNode != null) queue.Enqueue(t.LeftNode); if (t.RightNode != null) queue.Enqueue(t.RightNode); } }
六、深度的计算
public int deep(TreeNode root) { if (root == null) return 0; else { int deepLeft = 0; int deepRight = 0; deepLeft = deep(root.LeftNode); deepRight = deep(root.RightNode); return deepLeft > deepRight ? deepLeft + 1 : deepRight + 1; }
其他:叶子数的计算
前驱后继的获取(中序线索二叉树)
树森林-〉二叉树