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 89 90 91
| package com.example.demo;
import java.util.LinkedList;
public class Main {
static class TreeNode { int val; TreeNode left; TreeNode right;
TreeNode(int val) { this.val = val; }
TreeNode() { } }
static TreeNode buildTree(Object[] result, int index) { if (result[index] == null) { return null; }
TreeNode root = new TreeNode((Integer)result[index]); root.left = null; root.right = null;
int left = 2 * index + 1; int right = 2 * index + 2;
if (left > result.length - 1) { root.left = null; } else { root.left = buildTree(result, left);
}
if (right > result.length - 1) { root.right = null; } else { root.right = buildTree(result, right); } return root; }
static void preOrderTraverse(TreeNode root) { if (root == null) { return; } System.out.print(root.val + " "); preOrderTraverse(root.left); preOrderTraverse(root.right); }
static void levelOrderTraverse(TreeNode root) { LinkedList<TreeNode> queue = new LinkedList<>(); if (root == null) { return; } queue.addLast(root); while (!queue.isEmpty()) { TreeNode temp = queue.getFirst(); System.out.print(temp.val + " "); queue.removeFirst();
if (temp.left != null) { queue.addLast(temp.left); } if (temp.right != null) { queue.addLast(temp.right); } }
}
public static void main(String[] args) { Object[] result1 = {10, 5, 15, 3, 7, 13, 18, 1, null, 6}; preOrderTraverse(buildTree(result1, 0)); System.out.println(); levelOrderTraverse(buildTree(result1, 0)); System.out.println(); }
}
|