【算法训练】LeetCode#94 二叉树的中序遍历

一、描述

94. 二叉树的中序遍历

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

示例 1:

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

示例 2:

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

示例 3:

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

二、思路

链表题做的差不多了,开始做做栈吧,不过这道题其实不用栈实现更容易一些....

三、解题

public static class Solution {
    // 无递归,栈实现
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> ans = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        while (!stack.isEmpty() || root != null){
            if (root != null){
                stack.push(root);
                root = root.left;
            } else {
                root = stack.pop();
                ans.add(root.val);
                root = root.right;
            }
        }
        return ans;
    }

    // 递归遍历,直接入list
    public List<Integer> inorderTraversalV2(TreeNode root) {
        List<Integer> ans = new ArrayList<>();
        process(ans,root);
        return ans;
    }

    public void process(List<Integer> ans,TreeNode node){
        if (node == null){
            return;
        }
        process(ans,node.left);
        ans.add(node.val);
        process(ans,node.right);
    }
}
posted @ 2023-01-04 14:16  小拳头呀  阅读(11)  评论(0编辑  收藏  举报