前序遍历
递归版
/**
* 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 root) {
List<Integer> list = new ArrayList<>();
preorderTraversal(root, list);
return list;
}
public void preorderTraversal(TreeNode root, List<Integer> list){
if(root == null) return;
list.add(root.val);
preorderTraversal(root.left, list);
preorderTraversal(root.right, list);
}
}
非递归版
/**
* 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 root) {
List<Integer> list = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
if(root == null) return list;
stack.push(root);
while(!stack.empty()){
TreeNode node = stack.pop();
list.add(node.val);
// left
if(node.right != null){
stack.push(node.right);
}
// right
if(node.left != null){
stack.push(node.left);
}
}
return list;
}
}
中序遍历
递归版
/**
* 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.
*/
List<Integer> list = new ArrayList<>();
public List<Integer> inorderTraversal(TreeNode root) {
if(root == null) return list;
inorderTraversal(root.left);
list.add(root.val);
inorderTraversal(root.right);
return list;
}
}
非递归版
/**
* 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 root) {
Stack<TreeNode> stack = new Stack<>();
List<Integer> list = new ArrayList<>();
if(root == null) return list;
while(root != null){
stack.push(root);
root = root.left;
}
while(!stack.empty()){
TreeNode node = stack.peek();
list.add(node.val);
if(node.right == null){
node = stack.pop();
while(!stack.empty() && stack.peek().right == node){
node = stack.pop();
}
}
else{
node = node.right;
while(node != null){
stack.push(node);
node = node.left;
}
}
}
return list;
}
}