1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
| class Solution { protected internal class TreeNode { public TreeNode(int value) { this.Value = value; } public int Value { get; set; } public TreeNode Left { get; set; } public TreeNode Right { get; set; } }
public static TreeNode GetTree(params int[] arr) { Stack<int> stack = new Stack<int>(); Tuple<int, int>[] maxIndex = new Tuple<int, int>[arr.Length]; for (int i = 0; i < arr.Length; i++) { while (stack.Count != 0 && arr[stack.Peek()] < arr[i]) { int index = stack.Pop(); maxIndex[index] = new Tuple<int, int>(stack.Count == 0 ? -1 : stack.Peek(), i); } stack.Push(i); } while (stack.Count != 0) { int index = stack.Pop(); maxIndex[index] = new Tuple<int, int>(stack.Count == 0 ? -1 : stack.Peek(), -1); } TreeNode root = null; Dictionary<int, TreeNode> nodes = new Dictionary<int, TreeNode>(); for (int i = 0; i < maxIndex.Length; i++) { if (!nodes.ContainsKey(i)) { nodes[i] = new TreeNode(arr[i]); } var (left, right) = maxIndex[i]; if (left == -1 && right == -1) { root = nodes[i]; } else if (left != -1 && right != -1) { if (arr[left] < arr[right]) { if (!nodes.ContainsKey(left)) { nodes[left] = new TreeNode(arr[left]); } nodes[left].Right = nodes[i]; } else { if (!nodes.ContainsKey(right)) { nodes[right] = new TreeNode(arr[right]); } nodes[right].Left = nodes[i]; } } else { if (left != -1) { if (!nodes.ContainsKey(left)) { nodes[left] = new TreeNode(arr[left]); } nodes[left].Right = nodes[i]; } else { if (!nodes.ContainsKey(right)) { nodes[right] = new TreeNode(arr[right]); } nodes[right].Left = nodes[i]; } }
} return root; } }
|