只需以下五句代码排列组合即可解决二叉树的前序中序后序遍历问题:
res.add(root.val);
stack.push(root);
root=root.left;
TreeNode cur=stack.pop();
root=cur.right;
144. 二叉树的前序遍历
给你二叉树的根节点 root ,返回它节点值的 前序 遍历。
示例 1:
输入:root = [1,null,2,3] 输出:[1,2,3]
示例 2:
输入:root = [] 输出:[]
示例 3:
输入:root = [1] 输出:[1]
示例 4:
输入:root = [1,2] 输出:[1,2]
示例 5:
输入:root = [1,null,2] 输出:[1,2]
Java:
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
Deque<TreeNode> stack = new ArrayDeque<>();
while (root!=null||!stack.isEmpty()){
while(root!=null){
res.add(root.val);
stack.push(root);
root=root.left;
}
TreeNode cur=stack.pop();
root=cur.right;
}
return res;
}
}
145. 二叉树的后序遍历
给定一个二叉树,返回它的 后序 遍历。
示例:
输入: [1,null,2,3]
1
\
2
/
3
输出: [3,2,1]
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> res=new ArrayList<>();
Deque<TreeNode>stack=new ArrayDeque<>();
while(root!=null||!stack.isEmpty()){
while(root!=null){
res.add(root.val);
stack.push(root);
root=root.right;
}
TreeNode cur=stack.pop();
root=cur.left;
}
Collections.reverse(res);
return res;
}
}
94. 二叉树的中序遍历
给定一个二叉树的根节点 root ,返回它的 中序 遍历。
示例 1:
输入:root = [1,null,2,3] 输出:[1,3,2]
示例 2:
输入:root = [] 输出:[]
示例 3:
输入:root = [1] 输出:[1]
示例 4:
输入:root = [1,2] 输出:[2,1]
示例 5:
输入:root = [1,null,2] 输出:[1,2]
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res=new ArrayList<>();
Deque<TreeNode>stack=new ArrayDeque<>();
while(root!=null||!stack.isEmpty()){
while(root!=null){
stack.push(root);
root=root.left;
}
root=stack.pop();
res.add(root.val);
root=root.right;
}
return res;
}
}