二叉树创建
private static TreeNode createTree(String[] arr, int index) {
TreeNode tn = null;
if (index < arr.length) {
if (arr[index].equals("null")) {
return null;
}
Integer val = Integer.valueOf(arr[index]);
tn = new TreeNode(val);
tn.left = createTree(arr, 2 * index + 1);
tn.right = createTree(arr, 2 * index + 2);
}
return tn;
}
二叉树先序遍历
public void preOrderNone(TreeNode root) {
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while(!stack.isEmpty()) {
root = stack.pop();
System.out.println(root.val);
if(root.right!=null) {
stack.push(root.right);
}
if(root.left!=null) {
stack.push(root.left);
}
}
}
二叉树中序遍历
public void inOrder(TreeNode node) {
Stack<TreeNode> stack = new Stack<>();
while(node!=null || !stack.isEmpty()) {
while(node!=null) {
stack.push(node);
node = node.left;
}
if(!stack.isEmpty()) {
node = stack.pop();
System.out.println(node.val);
node = node.right;
}
}
}
后序遍历
private void postOrder(TreeNode root) {
Stack<TreeNode> stack = new Stack<>();
Stack<Integer> numStack = new Stack<>();
int left = 1;
int right = 2;
while(root!=null || !stack.isEmpty()) {
while(root!=null) {
stack.push(root);
numStack.push(left);
root = root.left;
}
if(!stack.isEmpty() && numStack.peek() == right) {
numStack.pop();
System.out.println(stack.pop().val);
}
if(!stack.isEmpty() && numStack.peek() == left) {
numStack.pop();
numStack.push(right);
root = stack.peek().right;
}
}
}
层序遍历
public void levelOrder(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
System.out.println(root.val);
while(!queue.isEmpty()) {
TreeNode node = queue.poll();
if(null!=node.left) {
queue.add(node.left);
}
if(null!=node.right) {
queue.add(node.right);
}
}
}
public void levelOrder1(TreeNode root) {
LinkedList<TreeNode> list = new LinkedList<>();
list.add(root);
while (!list.isEmpty()) {
root = list.poll();
System.out.println(root.val);
if (root.left != null)
list.offer(root.left);
if (root.right != null)
list.offer(root.right);
}
}
辅助方法
private static String[] stringToArray(String str) {
if (null != str && str.equals("")) {
return null;
}
String[] fields = str.split(",");
fields[0] = fields[0].substring(1);
int lastIndex = fields.length - 1;
fields[lastIndex] = fields[lastIndex].substring(0, 1);
return fields;
}
main方法
public static void main(String[] args) {
TreeNode root = stringToTree("[3,9,20,2,null,15,7]");
new StringToBinaryTree().postOrder(root);
}
public static TreeNode stringToTree(String str) {
String[] elems = stringToArray(str);
if (null == elems) {
return null;
}
TreeNode root = createTree(elems, 0);
return root;
}