/**
* @title TreeNode.java
* @description 二叉树节点
* @date 2014-05-04 22:38
* @author Administrator
* @version 1.0
*/
public class TreeNode {
private int val;
private TreeNode left;
private TreeNode right;
public TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
public int getVal() {
return val;
}
public void setVal(int val) {
this.val = val;
}
public TreeNode getLeft() {
return left;
}
public void setLeft(TreeNode left) {
this.left = left;
}
public TreeNode getRight() {
return right;
}
public void setRight(TreeNode right) {
this.right = right;
}
}
package cn.lcn.test;
import java.util.ArrayList;
import java.util.Stack;
/**
* @title Solution.java
* @description 解决方案
* @date 2014-05-04 22:44
* @author Administrator
* @version 1.0
*/
public class Solution {
public static ArrayList<Integer> preorderTraversal(TreeNode root) {
ArrayList<Integer> returnList = new ArrayList<Integer>();
if (root == null)
return returnList;
Stack<TreeNode> stack = new Stack<TreeNode>();
stack.push(root);
while (!stack.empty()) {
TreeNode n = stack.pop();
returnList.add(n.getVal());
if (n.getRight() != null) {
stack.push(n.getRight());
}
if (n.getLeft() != null) {
stack.push(n.getLeft());
}
}
return returnList;
}
public static TreeNode createTree(int[] input) {
TreeNode root = null;
TreeNode temp = null;
for (int i = 0; i < input.length; i++) {
if (root == null) {
root = temp = new TreeNode(input[i], null, null);// 创建根节点
} else {
temp = root;// 回到根结点
while (temp.getVal() != input[i]) {// 添加节点
if (input[i] <= temp.getVal()) {
if (temp.getLeft() != null) {
temp = temp.getLeft();
} else {
temp.setLeft(new TreeNode(input[i], null, null));
}
} else {
if (temp.getRight() != null) {
temp = temp.getRight();
} else {
temp.setRight(new TreeNode(input[i], null, null));
}
}
}
}
}
return root;
}
}
package cn.lcn.test;
import java.util.ArrayList;
/**
* @title Main.java
* @description 主测函数
* @date 2014-05-04 22:46
* @author Administrator
* @version 1.0
*/
public class Main {
public static void main(String[] args) {
int[] array = {12,76,35,22,16,48,90,46,9,40};
TreeNode root = Solution.createTree(array);
ArrayList<Integer> result = Solution.preorderTraversal(root);
System.out.println(">>>>>>>>先根遍历:");
for(Integer i : result){
System.out.println(i);
}
}
}