//最后输出节点元素 Console.Write(tree.data + "t"); } #endregion
#region 二叉树的按层遍历 /// <summary> /// 二叉树的按层遍历 /// </summary> /// <typeparam></typeparam> /// <param></param> public void BinTree_Level<T>(ChainTree<T> tree) { if (tree == null) return;
//申请保存空间 ChainTree<T>[] treeList = new ChainTree<T>[Length];
int head = 0; int tail = 0;
//存放数组 treeList[tail] = tree;
//循环链中计算tail位置 tail = (tail + 1) % Length;
while (head != tail) { var tempNode = treeList[head];
head = (head + 1) % Length;
//输出节点 Console.Write(tempNode.data + "t");
//如果左子树不为空,则将左子树存于数组的tail位置 if (tempNode.left != null) { treeList[tail] = tempNode.left;
tail = (tail + 1) % Length; }
//如果右子树不为空,则将右子树存于数组的tail位置 if (tempNode.right != null) { treeList[tail] = tempNode.right;
tail = (tail + 1) % Length; } } } #endregion
} }
我们把文章开头的“二叉树”的节点输入到我们的结构中,看看遍历效果咋样。
(编辑:焦作站长网)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|