לבנות עץ בינרי ממערך
יש לבנות עץ ממערך של מספרים
- public class TreeNod{
- public int? val;
- public TreeNode left; public TreeNode right;
- public TreeNode(int? x) { val = x; }
- }
- public static TreeNode toTreeNode(this int?[] tree) {
- if (tree.Length == 0) return null;
- TreeNode root = new TreeNode(tree[0]);
- Queue<TreeNode> q = new Queue<TreeNode>();
- q.Enqueue(root);
- for (int i = 1; i < tree.Length; i++) {
- TreeNode node = q.Peek();
- if (node.left == null) {
- node.left = new TreeNode(tree[i]);
- if (tree[i] != null) q.Enqueue(node.left);
- }
- else if (node.right == null) {
- node.right = new TreeNode(tree[i]);
- if (tree[i] != null) q.Enqueue(node.right);
- q.Dequeue();
- }
- }
- return root;
- }
- static void Main(string[] args) {
- int?[] arr = new int?[] {1, null, 0, 1 };
- TreeNode root = arr.toTreeNode();
- }