中序遍历
java
public List<Integer> inorderTraversal(TreeNode root) {
// List<Integer> result = new ArrayList<>();
// midAccTree(result,root);
// return result;
//栈迭代解决
List<Integer> result = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
while (root != null || !stack.isEmpty()){
while (root != null){
stack.push(root);
root = root.left;
}
root = stack.pop();
result.add(root.val);
root = root.right;
}
return result;
}
//中序遍历方法
// public void midAccTree(List<Integer> res,TreeNode root){
// if (root == null) return;
// midAccTree(res,root.left);
// res.add(root.val);
// midAccTree(res,root.right);
//
// }
后序遍历
java
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode preNode = null;
while (root != null || !stack.isEmpty()){
while (root != null){
stack.push(root);
root = root.left;
}
root = stack.pop();
if (root.right == null || root.right == preNode){
res.add(root.val);
preNode = root;
root = null;
}else {
stack.push(root);
root = root.right;
}
}
return res;
}