一个模板,只是换了一个输出的位置。
前序遍历
题目:https://leetcode-cn.com/problems/binary-tree-preorder-traversal/
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
if(root == null)
return new ArrayList<Integer>();
List<Integer> res = new ArrayList<Integer>();
Deque<TreeNode> stack = new LinkedList<>();
stack.push(root);
res.add(root.val);
while(!stack.isEmpty()){
while(root.left != null){
stack.push(root.left);
res.add(root.left.val); //将值添加到答案列表中
root = root.left;
}
TreeNode temp = stack.pop();
if(temp.right != null){
stack.push(temp.right);
res.add(temp.right.val); //将值添加到答案列表中
root = temp.right;
}
}
return res;
}
}
中序遍历
题目:https://leetcode-cn.com/problems/binary-tree-inorder-traversal/submissions/
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
if(root == null)
return new ArrayList<Integer>();
Deque<TreeNode> stack = new LinkedList<>();
List<Integer> res = new ArrayList<>();
stack.push(root);
while(!stack.isEmpty()){
while(root.left != null){
stack.push(root.left);
root = root.left;
}
TreeNode temp = stack.pop();
res.add(temp.val); //将值添加到答案列表中
if(temp.right != null){
stack.push(temp.right);
root = temp.right;
}
}
return res;
}
}
后序遍历
前序遍历是 根左右,后序遍历是左右根。
那如果让前序遍历是根右左,倒过来不就是根左右了吗。
只需要把左右循序换一下,然后结果插入在结果集的最前方(相当于倒过来输出)
题目:https://leetcode-cn.com/problems/binary-tree-postorder-traversal/submissions/
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
if(root == null)
return new ArrayList<Integer>();
List<Integer> res = new ArrayList<>();
Deque<TreeNode> stack = new LinkedList<>();
stack.push(root);
res.add(root.val);
System.out.println(root.val);
while(!stack.isEmpty()){
while(root.right != null){
stack.push(root.right);
res.add(0, root.right.val); //将值添加到答案列表中
System.out.println(root.right.val);
root = root.right;
}
TreeNode temp = stack.pop();
if(temp.left != null){
stack.push(temp.left);
System.out.println(temp.left.val);
res.add(0, temp.left.val); //将值添加到答案列表中
root = temp.left;
}
}
return res;
}
}