问题一:
后序遍历
题目描述
求给定的二叉树的后序遍历。
例如:
给定的二叉树为{1,#,2,3},
1↵ ↵ 2↵ /↵ 3↵
返回[3,2,1].
备注;用递归来解这道题太没有新意了,可以给出迭代的解法么?
Given a binary tree, return the postorder traversal of its nodes' values.
For example:
Given binary tree{1,#,2,3},
1↵ ↵ 2↵ /↵ 3↵
return[3,2,1].
Note: Recursive solution is trivial, could you do it iteratively?
解题思路:关于树的遍历,首先想到的是递归实现,但是题目要求不使用递归;
可以考虑栈的数据结构,先进去的后遍历,后进来的先遍历
注意后序遍历最后需要翻转一下
import java.util.ArrayList; import java.util.Stack; import java.util.Collections; /** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public ArrayList<Integer> postorderTraversal(TreeNode root) { if(root == null){ return new ArrayList<Integer>(); } ArrayList<Integer> list = new ArrayList<Integer>(); Stack<TreeNode> stack = new Stack<TreeNode>(); stack.push(root); while(!stack.isEmpty()){ TreeNode node = stack.pop(); list.add(node.val); if(node.left != null){ stack.push(node.left); } if(node.right != null){ stack.push(node.right); } } Collections.reverse(list); return list; } }
问题二:
先序遍历,
思路:同样采用栈实现
import java.util.ArrayList; import java.util.Stack; /** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public ArrayList<Integer> preorderTraversal(TreeNode root) { if(root == null){ return new ArrayList<Integer>(); } ArrayList<Integer> list = new ArrayList<Integer>(); Stack<TreeNode> stack = new Stack<TreeNode>(); stack.push(root); while(!stack.isEmpty()){ TreeNode node = stack.pop(); list.add(node.val); if(node.right != null){ stack.push(node.right); } if(node.left != null){ stack.push(node.left); } } return list; } }