二叉树的前中后 递归与非递归遍历
一、前序
class Solution {
List<Integer> res;
public List<Integer> preorderTraversal(TreeNode root) {
res = new ArrayList<>();
dfs(root);
return res;
}
public void dfs(TreeNode root){
if(root == null)return;
res.add(root.val);
dfs(root.left);
dfs(root.right);
}
}
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
Stack<TreeNode> stk = new Stack<>();
if(root == null)return res;
stk.push(root);
while(!stk.isEmpty()){
TreeNode t = stk.pop();
if(t != null){
if(t.right != null)stk.push(t.right);
if(t.left != null)stk.push(t.left);
}
res.add(t.val);
}
return res;
}
}
二、后序
class Solution {
List<Integer> res = new ArrayList<>();
public List<Integer> postorderTraversal(TreeNode root) {
if(root == null)return res;
dfs(root);
return res;
}
public void dfs(TreeNode root){
if(root == null)return;
dfs(root.left);
dfs(root.right);
res.add(root.val);
}
}
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
Stack<TreeNode> stk = new Stack<>();
Stack<Integer> help = new Stack<>();
if(root == null)return res;
stk.push(root);
while(!stk.isEmpty()){
TreeNode t = stk.pop();
if(t != null){
if(t.left != null)stk.push(t.left);
if(t.right != null)stk.push(t.right);
}
// System.out.println(t.val);
help.push(t.val);
}
while(!help.isEmpty())res.add(help.pop());
return res;
}
}
三、中序
class Solution {
List<Integer> res = new ArrayList<>();
public List<Integer> inorderTraversal(TreeNode root) {
if(root == null)return res;
dfs(root);
return res;
}
public void dfs(TreeNode root){
if(root == null)return;
dfs(root.left);
res.add(root.val);
dfs(root.right);
}
}
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
Stack<TreeNode> stk = new Stack<>();
TreeNode cur = root;
if(cur == null)return res;
while(cur != null || !stk.isEmpty()){
if(cur != null){
stk.push(cur);
cur = cur.left;
}else{
TreeNode t = stk.pop();
res.add(t.val);
cur = t.right;
}
}
return res;
}
}