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
| public class Solution_0064 {
public static TreeNode recurTree(int[] preorder, int preLeft, int preRight, int[] inorder, int inLeft, int inRight) {
TreeNode root = new TreeNode(preorder[preLeft]);
int rootIndex = 0;
for (int i = inLeft; i < inRight + 1; i++) {
if(inorder[i] == root.val) { rootIndex = i; break; } }
int preIndex = rootIndex - 1 - inLeft + 1; preIndex = preLeft + 1 + preIndex - 1;
if(rootIndex == inLeft) root.left = null; else root.left = recurTree(preorder, preLeft + 1, preIndex, inorder, inLeft, rootIndex - 1);
if(rootIndex == inRight) root.right = null; else root.right = recurTree(preorder, preIndex + 1, preRight, inorder, rootIndex + 1, inRight);
return root; }
public static TreeNode buildTree(int[] preorder, int[] inorder) {
return recurTree(preorder, 0, preorder.length - 1, inorder, 0, inorder.length - 1); }
public static void main(String[] args) { System.out.println();
int[] inorder = {9, 3, 15, 20, 7}; int[] pretorder = {3, 9, 20, 15, 7};
TreeNode root = buildTree(pretorder, inorder);
TreeNode root = buildTree(pretorder, inorder);
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while(queue.size() > 0) { int length = queue.size();
while(length-- > 0) {
root = queue.poll(); System.out.print(root.val + "\t");
if(root.left != null) queue.offer(root.left); if(root.right != null) queue.offer(root.right); } } } }
|