LC94——二叉树的中序遍历

61 阅读1分钟

二叉树的中序遍历

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

示例 1:

输入:root = [1,null,2,3] 输出:[1,3,2] 示例 2:

输入:root = [] 输出:[] 示例 3:

输入:root = [1] 输出:[1]

提示:

树中节点数目在范围 [0, 100] 内 -100 <= Node.val <= 100

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

解答:

  • 中序,先左子树、根、右子树

  • 递归

  • 非递归

  • 递归

    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        if (root == null) return list;
        List<Integer> llist = inorderTraversal(root.left);
        if (llist != null) list.addAll(llist);
        list.add(root.val);
        List<Integer> rlist = inorderTraversal(root.right);
        if (rlist != null) list.addAll(rlist);
        return list;
    }
  • 迭代
    public List<Integer> inorderTraversal(TreeNode root) {
        //迭代算法
        List<Integer> list = new ArrayList<>();
        if (root == null) return list;
        Stack<TreeNode> stack = new Stack<>();
        TreeNode node = root;
        //或
        while (node != null || !stack.isEmpty()) {
            while (node != null) {
                stack.push(node);
                node = node.left;
            }
            if (!stack.isEmpty()) {
                node = stack.pop();
                list.add(node.val);
                node = node.right;//这个不是push
            }
        }
        return list;
    }

扩展:

  • 先序遍历,根左右,一套迭代模版
    public List<Integer> preorderTraversal(TreeNode root) {
        //迭代算法
        List<Integer> list = new ArrayList<>();
        if (root == null) return list;
        Stack<TreeNode> stack = new Stack<>();
        TreeNode node = root;
        
        while (node != null || !stack.isEmpty()) {
            while (node != null) {
                stack.push(node);
                list.add(node.val);
                node = node.left;
            }
            if (!stack.isEmpty()) {
                node = stack.pop();
                node = node.right;//这个不是push
            }
        }
        return list;
    }
  • 后序遍历,左右根;使用双栈,先遍历根、右、左,然后利用另一个栈反转即是左、右、根的后序顺序
    public List<Integer> postorderTraversal(TreeNode root) {
        //迭代算法
        List<Integer> list = new ArrayList<>();
        if (root == null) return list;
        Stack<TreeNode> stack = new Stack<>();
        Stack<TreeNode> result = new Stack<>();
        TreeNode node = root;
        
        while (node != null || !stack.isEmpty()) {
            while (node != null) {
                stack.push(node);
                result.push(node.val);
                node = node.right;
            }
            if (!stack.isEmpty()) {
                node = stack.pop();
                node = node.left;
            }
        }
        while(!result.isEmpty()) {
           list.add(result.pop());
        }
        return list;
    }