在做劍指offer的題目時,發現每次需要用到樹做為引數來測驗自己寫的方法時,都很是痛苦,于是乎就萌生了寫一個利用陣列作為引數生成樹的方法,簡單測驗了下,沒什么毛病,在這里貼出來,如果以后發現有bug了會持續在后面更新,也歡迎大家指出其中的不足,
public class TreeNode
{
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int x)
{
val = x;
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace offerTest.Helper
{
class TreeHelper
{
/// <summary>
/// 根據陣列按順序從上到下生成樹
/// </summary>
/// <param name="arrayTree">生成樹的節點資料,無節點的位置需要設定為null,一個有值的節點必須設定兩個左右子節點,</param>
/// <returns></returns>
public static TreeNode CreateTreeByArry(int?[] arrayTree)
{
Queue<TreeNode> treeNodes = new Queue<TreeNode>();
if(arrayTree==null ||!arrayTree[0].HasValue)
{
throw new ArgumentException("生成樹的根節點不能為null");
}
var root = new TreeNode(arrayTree[0].Value);
treeNodes.Enqueue(root);
CreateTree(arrayTree, 1, treeNodes);
return root;
}
/// <summary>
/// 為父節點賦左右子節點值,null父節點不操作,
/// </summary>
/// <param name="arrayTree">資料源</param>
/// <param name="StartIndex">開始填充的值的索引</param>
/// <param name="Qroot">需要賦子節點的父節點佇列</param>
/// <returns></returns>
public static bool CreateTree(int?[] arrayTree, int StartIndex, Queue<TreeNode> Qroot)
{
if (StartIndex > 0 && arrayTree.Count() > StartIndex)
{
Queue<TreeNode> treeNodes = new Queue<TreeNode>();
foreach(var root in Qroot)
{
//為null代表該節點沒有
if (root == null)
continue;
if(arrayTree.Count() > StartIndex)
{
if (arrayTree[StartIndex].HasValue)
root.left = new TreeNode(arrayTree[StartIndex].Value);
else
root.left = null;
}
if (arrayTree.Count() > StartIndex + 1)
{
if (arrayTree[++StartIndex].HasValue)
root.right = new TreeNode(arrayTree[StartIndex].Value);
else
root.right = null;
}
else
return false;
//將父節點放入佇列,
treeNodes.Enqueue(root.left);
treeNodes.Enqueue(root.right);
StartIndex += 1;
}
return !CreateTree(arrayTree, StartIndex, treeNodes);
}
else
return false;
}
}
}
怎么使用呢?一張自畫圖體會一下

轉載請註明出處,本文鏈接:https://www.uj5u.com/net/47027.html
標籤:.NET Core
下一篇:net core System.Drawing is not supported on this platform.
