zoukankan      html  css  js  c++  java
  • 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;
        }
    }
  • 相关阅读:
    第三周java学习总结
    第一周Java学习总结
    关闭窗体
    乱七八糟
    网页游戏资料
    timer控件的使用
    spread 签套循环改变颜色编号为颜色
    限制输入‘号的代码
    SQlcharindex命令
    限制输入类型
  • 原文地址:https://www.cnblogs.com/fatttcat/p/10204202.html
Copyright © 2011-2022 走看看