一个模板,只是res.add位置的改变
1,前序
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();//存结果
Stack<TreeNode> stack = new Stack<>();//用栈辅助
while(root != null){//一路向左入栈
res.add(root.val);//前序遇到根节点则遍历根节点
stack.push(root);
root = root.left;
}
while(!stack.isEmpty()){//弹出一个,若有右孩子,则入栈,这里不用考虑左孩子了,因为前面的第一个循环已经全进去了左节点
TreeNode t = stack.pop();
TreeNode r = t.right;
while(r!=null){
res.add(r.val);//前序遍历,遇到则加右孩子
stack.push(r);
r = r.left;
}
}
return res;
}
}
2,中序
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
while(root != null){//一路向左,给它把左边的节点都入栈
stack.push(root);
root = root.left;
}
while(!stack.isEmpty()){
TreeNode t = stack.pop();
res.add(t.val);//只需要在栈弹出的时候记录就行
TreeNode r = t.right;
while(r!=null){
//加这一行是错的,res.add(r.val);
stack.push(r);
r = r.left;
}
}
return res;
}
}
3,后续
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
//先让右孩子入栈,得到 根 右 左---> 逆置一下----->左 右 根
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
while(root != null){
res.add(root.val);
stack.push(root);
root = root.right;
}
while(!stack.isEmpty()){
TreeNode t = stack.pop();
TreeNode r = t.left;
while(r!=null){
res.add(r.val);
stack.push(r);
r = r.right;
}
}
Collections.reverse(res);
return res;
}
}