加入收藏 | 设为首页 | 会员中心 | 我要投稿 焦作站长网 (https://www.0391zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 服务器 > 安全 > 正文

算法系列15天速成 第十一天 树操作(上)

发布时间:2020-03-14 19:10:46 所属栏目:安全 来源:站长网
导读:我们可以对”线性结构“改造一下,变为”一个节点最多有一个前驱“和”多个后继“。哈哈,这就是我们今天说的”树“

//最后输出节点元素
            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

}
}

我们把文章开头的“二叉树”的节点输入到我们的结构中,看看遍历效果咋样。

(编辑:焦作站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

热点阅读