66. 二叉树的前序遍历
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root: A Tree
* @return: Preorder in ArrayList which contains node values.
*/
public List<Integer> preorderTraversal(TreeNode treeNode) {
// write your code here
List<Integer> integerList = new ArrayList<>();
Stack<TreeNode> stack = new Stack<TreeNode>();
while (treeNode != null || !stack.isEmpty()) {
while (treeNode != null) {
integerList.add(treeNode.val);
stack.push(treeNode);
treeNode = treeNode.left;
}
if (!stack.isEmpty()) {
treeNode = stack.pop();
treeNode = treeNode.right;
}
}
return integerList;
}
}
67. 二叉树的后序遍历
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root: A Tree
* @return: Postorder in ArrayList which contains node values.
*/
public List<Integer> postorderTraversal(TreeNode treeNode) {
List<Integer> integerList = new ArrayList<>();
// write your code here
Stack<TreeNode> stack = new Stack<TreeNode>();
while (treeNode != null || !stack.isEmpty()) {
while (treeNode != null) {
stack.push(treeNode);
treeNode = treeNode.left;
}
boolean tag = true;
TreeNode preNode = null; // 前驱节点
while (!stack.isEmpty() && tag == true) {
treeNode = stack.peek();
if (treeNode.right == preNode) { // 之前访问的为空节点或是栈顶节点的右子节点
treeNode = stack.pop();
integerList.add(treeNode.val);
if (stack.isEmpty()) {
return integerList;
} else {
preNode = treeNode;
}
} else {
treeNode = treeNode.right;
tag = false;
}
}
}
return integerList;
}
}
67. 二叉树的中序遍历
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root: A Tree
* @return: Inorder in ArrayList which contains node values.
*/
public List<Integer> inorderTraversal(TreeNode treeNode) {
// write your code here
List<Integer> integerList = new ArrayList<>();
Stack<TreeNode> stack = new Stack<TreeNode>();
while (treeNode != null || !stack.isEmpty()) {
while (treeNode != null) {
stack.push(treeNode);
treeNode = treeNode.left;
}
if (!stack.isEmpty()) {
treeNode = stack.pop();
integerList.add(treeNode.val);
treeNode = treeNode.right;
}
}
return integerList;
}
}