leetcode94-二叉树的中序遍历

原题

给定一个二叉树,返回它的 中序 遍历。

示例:

输入: [1,null,2,3]  1
  \
   2
  /
 3
输出: [1,3,2]

进阶: 递归算法很简单,你可以通过迭代算法完成吗?

解法

思想

DFS,递归方法着实很简单,迭代很抽象。

代码

递归:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    List<Integer> ans = new ArrayList<>();
    public List<Integer> inorderTraversal(TreeNode root) {
        if(root!=null){
            inorderTraversal(root.left);
            ans.add(root.val);
            inorderTraversal(root.right);
        }
        return ans;
    }
}

迭代,我一开始这么写的,用一个HashSet记录栈存储过的节点:

class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        Stack<TreeNode> stack = new Stack<>();
        List<Integer> ans = new ArrayList<>();
        Set<TreeNode> set = new HashSet<>();
        stack.push(root);
        if(root == null) return ans;
        while(!stack.empty()){
            TreeNode node = stack.peek();
            if(null!=node.left && !set.contains(node.left)) {
                stack.push(node.left);
                set.add(node.left);
            }
            else{
                ans.add(node.val);
                stack.pop();
                if(null!=node.right) 
                    stack.push(node.right);
                node = null;
            }
        }
        return ans;
    }
}

然后看到官方的写法,这才是递归转化过来的写法:

public class Solution {
    public List <Integer> inorderTraversal(TreeNode root) {
        List <Integer> res = new ArrayList<>();
        Stack <TreeNode> stack = new Stack<>();
        TreeNode curr = root;
        while (curr != null || !stack.isEmpty()) {
            while (curr != null) {
                stack.push(curr);
                curr = curr.left;
            }
            curr = stack.pop();
            res.add(curr.val);
            curr = curr.right;
        }
        return res;
    }
}

原创文章,作者:彭晨涛,如若转载,请注明出处:https://www.codetool.top/article/leetcode94-%e4%ba%8c%e5%8f%89%e6%a0%91%e7%9a%84%e4%b8%ad%e5%ba%8f%e9%81%8d%e5%8e%86/