前序中序構建二叉樹
阿新 • • 發佈:2017-05-24
[] pri light index blog log highlight tree cnblogs
public Node PreMidToTree(int[] pre,int[] mid) { if (pre == null || mid == null) return; Dictionary<int, int> dic = new Dictionary<int, int>(); for (int i = 0; i < mid.Length; i++) dic[mid[i]] = i; return PreMid(pre, 0, pre.Length - 1, mid, 0, mid.Length - 1, dic); } private Node PreMid(int[] pre, int ps, int pe, int[] mid, int ms, int me, Dictionary<int, int> dic) { if (ps > pj) return null; Node head = new Node(p[pi]); int index = dic[pre[ps]]; head.left = PreMid(pre,ps+1,ps+index-ms,mid,ms,index-1,dic); head.right = PreMid(pre, ps + 1, ps + index - ms, mid, ms, index - 1, dic); return head; }
前序中序構建二叉樹