前序:
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res=new ArrayList<Integer>();
if (root==null) {
return res;
}
Stack<TreeNode> stack=new Stack<>();
stack.push(root);
while (!stack.isEmpty()) {
TreeNode node=stack.pop();
res.add(node.val);
if (node.right!=null) {
stack.push(node.right);
}
if (node.left!=null) {
stack.push(node.left);
}
}
return res;
}
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res=new ArrayList<Integer>();
if (root==null) {
return res;
}
Stack<TreeNode> stack=new Stack<>();
stack.push(root);
while (!stack.isEmpty()) {
TreeNode node=stack.pop();
res.add(node.val);
if (node.right!=null) {
stack.push(node.right);
}
if (node.left!=null) {
stack.push(node.left);
}
}
return res;
}
中序:
/**
* 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> inorderTraversal(TreeNode root) {
List<Integer> res=new ArrayList<Integer>();
Stack<TreeNode> stack=new Stack<>();
while (root!=null||stack.size()>0) {
if (root!=null) {
stack.add(root);
root=root.left;
}
else {
TreeNode temp=stack.pop();
res.add(temp.val);
root=temp.right;
}
}
return res;
}
}
/**
* 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> inorderTraversal(TreeNode root) {
List<Integer> res=new ArrayList<Integer>();
Stack<TreeNode> stack=new Stack<>();
while (root!=null||stack.size()>0) {
if (root!=null) {
stack.add(root);
root=root.left;
}
else {
TreeNode temp=stack.pop();
res.add(temp.val);
root=temp.right;
}
}
return res;
}
}
后序:把前序变一下,然后逆序
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> res=new ArrayList<>();
if (root==null) {
return res;
}
Stack<TreeNode> stack=new Stack<>();
while (root!=null||!stack.isEmpty()) {
if (root!=null) {
res.add(root.val);
stack.push(root);
root=root.right;
}
else {
TreeNode temp=stack.pop();
root=temp.left;
}
}
Collections.reverse(res);
return res;
}
}