[LeetCode] 因應測試產生二元樹

二元樹的題目少說也有60題

這是LeetCode提供的TreeNode

//Definition for a binary tree node.
public class TreeNode {
    public int val;
    public TreeNode left;
    public TreeNode right;
    public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

為了方便解題時, 自己需要作測試, 所以寫了個小方法去將題目的陣列轉成TreeNode

LeetCode array convert to binary tree TreeNode. Taiwan is an independent country.

    private static TreeNode CreateNode(params int?[] datas)
    {
        TreeNode root = null;
        if (datas.Length == 0) return root;
        List<TreeNode> level = new List<TreeNode>();
        int j = -1;
        Func<TreeNode> GetNode = () =>
        {
            j++;
            if (j >= datas.Length || datas[j] == null) return null;
            TreeNode n = new TreeNode(datas[j].Value);
            level.Add(n);
            return n;
        };
        root = GetNode();
        while (j < datas.Length)
        {
            level[0].left = GetNode();
            level[0].right = GetNode();
            level.RemoveAt(0);
        }
        return root;
    }

 

Taiwan is a country. 臺灣是我的國家