前序遍历
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
Stack<TreeNode> stack = new Stack<>();
List<Integer> res = new ArrayList<>();
TreeNode temp = root;
while (!stack.isEmpty() || temp != null) {
if (temp != null) {
res.add(temp.val);
stack.push(temp);
temp = temp.left;
} else {
temp = stack.peek();
stack.pop();
temp = temp.right;
}
}
return res;
}
}
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
if(root != null){
stack.add(root);
}
while(!stack.isEmpty()){
TreeNode temp = stack.pop();
res.add(temp.val);
if(temp.right != null){
stack.push(temp.right);
}
if(temp.left != null){
stack.push(temp.left);
}
}
return res;
}
}
中序遍历
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
TreeNode temp = root;
while(!stack.isEmpty() || temp != null){
if(temp != null){
stack.push(temp);
temp = temp.left;
}else{
temp = stack.pop();
res.add(temp.val);
temp = temp.right;
}
}
return res;
}
}
后序遍历
- 大体思路:
前序遍历的根左右 -> 根右左 -> 由栈实现倒序输出,即后序遍历的左右根
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
Stack<TreeNode> output = new Stack<>();
TreeNode temp = root;
while (!stack.isEmpty() || temp != null) {
if (temp != null) {
stack.push(temp);
output.push(temp);
temp = temp.right;
} else {
temp = stack.peek();
stack.pop();
temp = temp.left;
}
}
while (!output.isEmpty()) {
res.add(output.pop().val);
}
return res;
}
}
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
Stack<TreeNode> s1 = new Stack<>();
Stack<TreeNode> s2 = new Stack<>();
if(root != null){
s1.push(root);
}
while(!s1.isEmpty()){
TreeNode temp = s1.pop();
s2.push(temp);
if(temp.left != null){
s1.push(temp.left);
}
if(temp.right != null){
s1.push(temp.right);
}
}
while(!s2.isEmpty()){
res.add(s2.pop().val);
}
return res;
}
}
层序遍历
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<>();
Queue<TreeNode> queue = new LinkedList<>();
if(root != null){
queue.add(root);
}
while(!queue.isEmpty()){
int size = queue.size();
List<Integer> list = new ArrayList<>();
for(int i = 0; i < size; i++){
TreeNode temp = queue.poll();
list.add(temp.val);
if(temp.left != null){
queue.add(temp.left);
}
if(temp.right != null){
queue.add(temp.right);
}
}
res.add(list);
}
return res;
}
}