94.二叉树的前序遍历
思路:可以使用递归和迭代两种方式完成,而迭代方式实际上是借助栈来完成递归。
递归:
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList();
preorder(root, result);
return result;
}
public void preorder(TreeNode root, List<Integer> result) {
if(root == null) {
return;
}
result.add(root.val);
preorder(root.left, result);
preorder(root.right, result);
}
}
迭代:
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
Stack<TreeNode> stack = new Stack();
List<Integer> result = new ArrayList();
if(root == null) {
return result;
}
stack.push(root);
while(!stack.isEmpty()) {
TreeNode node = stack.pop();
result.add(node.val);
if(node.right != null) {
stack.push(node.right);
}
if(node.left != null) {
stack.push(node.left);
}
}
return result;
}
}
小结:值得注意的点
- 在递归中要分析递归函数的参数及返回值、递归结束的条件、单层递归的处理逻辑
- 在迭代中,首先对栈顶的元素(即对应的根节点)进行操作。用栈来存放对应的节点,List来存放遍历的结果
144.二叉树的后序遍历
思路:可以使用递归和迭代两种方式完成。在迭代方式中,后序遍历是:左->右->中,通过入栈顺序为:中->左->右便可得到出栈顺序为:中->右->左,最后翻转结果就可以得到后序遍历
递归:
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList();
postorder(root, result);
return result;
}
public void postorder(TreeNode root, List<Integer> result) {
if(root == null) {
return;
}
postorder(root.left, result);
postorder(root.right, result);
result.add(root.val);
}
}
迭代:
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
Stack<TreeNode> stack = new Stack();
List<Integer> result = new ArrayList();
if(root == null) {
return result;
}
stack.push(root);
while(!stack.isEmpty()) {
TreeNode node = stack.pop();
result.add(node.val);
if(node.left != null) {
stack.push(node.left);
}
if(node.right != null) {
stack.push(node.right);
}
}
Collections.reverse(result);
return result;
}
}
小结:值得注意的点
- 在迭代法中,调整相应的结构,再通过翻转便可得到答案。有时正面思考不容易得到答案时,应该从反面出发
145.二叉树的中序遍历
思路:可以使用递归和迭代两种方式完成。但在中序遍历中,无法通过调整前序遍历的迭代代码来实现。其原因在于前序遍历中:要访问的元素和要处理的元素顺序是一致的。而在中序遍历中:处理顺序和访问顺序是不一致的。因此在使用迭代法写中序遍历,就需要借用指针的遍历来帮助访问节点,栈则用来处理节点上的元素。
递归:
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList();
inorder(root, result);
return result;
}
public void inorder(TreeNode root, List<Integer> result) {
if(root == null) {
return;
}
inorder(root.left, result);
result.add(root.val);
inorder(root.right, result);
}
}
迭代:
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList();
Stack<TreeNode> stack = new Stack();
if (root == null){
return result;
}
TreeNode cur = root;
while (cur != null || !stack.isEmpty()){
if (cur != null){
stack.push(cur);
cur = cur.left;
}else{
cur = stack.pop();
result.add(cur.val);
cur = cur.right;
}
}
return result;
}
}
小结:值得注意的点
- 在迭代法中,先要从根节点到达左子树的最深处,然后从栈中弹出栈顶元素来依次进行访问