leetcode有相关的题目
转一个我觉得写的很清楚的题解:
https://leetcode-cn.com/problems/binary-tree-preorder-traversal/solution/leetcodesuan-fa-xiu-lian-dong-hua-yan-shi-xbian-2/
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class Search {
private List<Integer> list; //存储最后的结果
//前序 递归算法
public List<Integer> preorderTraversal1(TreeNode root) {
list = new ArrayList<>();
preVisit(root);
return list;
}
public void preVisit(TreeNode root){
if(root == null) return;
else{
list.add(root.val);
preVisit(root.left);
preVisit(root.right);
}
}
//前序 迭代算法
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
if(root==null) return res;
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while (!stack.empty()){
TreeNode pop = stack.pop();
res.add(pop.val);
if(pop.right !=null)
stack.push(pop.right);
if(pop.left !=null)
stack.push(pop.left);
}
return res;
}
//中序 递归算法
public List<Integer> inorderTraversal1(TreeNode root) {
list = new ArrayList<>();
inorderVisit(root);
return list;
}
public void inorderVisit(TreeNode root){
if(root == null) return;
else{
inorderVisit(root.left);
list.add(root.val);
inorderVisit(root.right);
}
}
//中序 迭代算法
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
TreeNode cur = root;
while(cur!=null || !stack.empty()){
while (cur!=null){
stack.push(cur);
cur = cur.left;
}
TreeNode pop = stack.pop();
res.add(pop.val);
if(pop.right!=null){
cur=pop.right;
}
}
return res;
}
//后序 递归算法
public List<Integer> postorderTraversal1(TreeNode root) {
list = new ArrayList<>();
postVisit(root);
return list;
}
public void postVisit(TreeNode root){
if(root == null) return;
else{
postVisit(root.left);
postVisit(root.right);
list.add(root.val);
}
}
//后序 迭代算法
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
if(root == null )return res;
Stack<TreeNode> stack = new Stack<>();
TreeNode reNode = root;
stack.push(root);
while(!stack.empty()){
TreeNode cur = stack.peek();
if(cur.left!=reNode && cur.right!=reNode && cur.left!=null){
stack.push(cur.left);
}
else if(cur.right!=reNode && cur.right!=null){
stack.push(cur.right);
}
else{
res.add(cur.val);
stack.pop();
reNode=cur;
}
}
return res;
}
}