/**
* 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<Integer>();
preorder(root,res);
return res;
}
public void preorder(TreeNode node,List<Integer> li){
if (node == null){
return;
}
li.add(node.val);
preorder(node.left,li);
preorder(node.right,li);
}
}
//递归
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
Stack<TreeNode> stk = new Stack<>();
List<Integer> res = new ArrayList<>();
stk.push(root);
while(!stk.isEmpty()){
TreeNode tmp = stk.pop();
if(tmp == null){
continue;
}else{
res.add(tmp.val);
stk.push(tmp.right);
stk.push(tmp.left);
}
}
return res;
}
}
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
postorder(root,res);
return res;
}
public void postorder(TreeNode node, List<Integer> li){
if (node == null){
return;
}
postorder(node.left,li);
postorder(node.right,li);
li.add(node.val);
}
}
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
Stack<TreeNode> stk = new Stack<>();
List<Integer> res = new ArrayList<>();
stk.push(root);
while(!stk.isEmpty()){
TreeNode tmp = stk.pop();
if(tmp == null){
continue;
}else{
res.add(tmp.val);
//相对于前序,调换left和right的顺序 -->中右左
stk.push(tmp.left);
stk.push(tmp.right);
}
}
//最后翻转-->左右中
Collections.reverse(res);
return res;
}
}
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
inorder(root,res);
return res;
}
public void inorder(TreeNode root,List<Integer> res){
if (root==null){
return;
}
inorder(root.left,res);
res.add(root.val);
inorder(root.right,res);
}
}
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
Stack<TreeNode> stk = new Stack<>();
List<Integer> res = new ArrayList<>();
TreeNode cur = root;
while(cur != null || !stk.isEmpty()){
if(cur != null){
stk.add(cur);
cur = cur.left;
}else{
TreeNode tmp = stk.pop();
res.add(tmp.val);
cur = tmp.right;
}
}
return res;
}
}