• 94. Binary Tree Inorder Traversal


    Given a binary tree, return the inorder traversal of its nodes' values.

    Example:

    Input: [1,null,2,3]
       1
        
         2
        /
       3
    
    Output: [1,3,2]

    Follow up: Recursive solution is trivial, could you do it iteratively?

    M1: recursive

    time: O(n), space: O(height)

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

    M2: iterative

    time: O(n), space: O(n)  -- worst case

    class Solution {
        public List<Integer> inorderTraversal(TreeNode root) {
            List<Integer> res = new ArrayList<>();
            if(root == null) {
                return res;
            }
            LinkedList<TreeNode> stack = new LinkedList<>();
            TreeNode cur = root;
            while(cur != null || !stack.isEmpty()) {
                while(cur != null) {
                    stack.offerFirst(cur);
                    cur = cur.left;
                }
                cur = stack.pollFirst();
                res.add(cur.val);
                cur = cur.right;
            }
            return res;
        }
    }
  • 相关阅读:
    MapReduce TFIDF 案列
    MapReduce PageRank案列
    MapReduce好友推荐案例
    MapReduce天气查询实列
    MapReduce源码分析
    Tiny6410之LED裸机驱动
    Linux -- objdump (待继续完善)
    Linux -- xxd 整理自man 手册 (MARK)
    Linux -- xxd (转)
    tar -- 打包压缩文件
  • 原文地址:https://www.cnblogs.com/fatttcat/p/10204202.html
Copyright © 2020-2023  润新知