LeetCode 145. 前中后序遍历 非递归 Java
原题链接
简单
作者:
henhen敲
,
2020-06-20 12:34:21
,
所有人可见
,
阅读 917
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
前序遍历
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
Stack<TreeNode> stack = new Stack<>();
List<Integer> ans = new ArrayList<>();
while(root!=null||!stack.isEmpty()){
while(root!=null){
ans.add(root.val);
stack.push(root);
root = root.left;
}
root = stack.pop().right;
}
return ans;
}
}
中序遍历
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
Stack<TreeNode> stack = new Stack<>();
List<Integer> ans = new ArrayList<>();
while(root!=null||!stack.isEmpty()){
while(root!=null){
stack.push(root);
root = root.left;
}
root = stack.pop();
ans.add(root.val);
root = root.right;
}
return ans;
}
}
后序遍历
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
Stack<TreeNode> stack = new Stack<>();
List<Integer> ans = new ArrayList<>();
HashMap<TreeNode, Integer> map = new HashMap<>();
while(root!=null||!stack.isEmpty()){
while(root!=null){
stack.push(root);
map.put(root, map.getOrDefault(root, 0)+1);
root = root.left;
}
root = stack.pop();
int flag = map.get(root);
if(flag<2){
stack.push(root);
map.put(root, map.getOrDefault(root, 0)+1);
root = root.right;
}
else{
ans.add(root.val);
root = null;
}
}
return ans;
}
}
It is a best solution found that very popular and helpful:
https://www.youtube.com/watch?v=0VQSwssqRqk&ab_channel=EricProgramming