zoukankan      html  css  js  c++  java
  • 【LeetCode】94. Binary Tree Inorder Traversal

    Difficulty: Medium

     More:【目录】LeetCode Java实现

    Description

    https://leetcode.com/problems/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?

    Intuition

    1. Recursion

    2. Iteration

    Solution

    Recursion

        public List<Integer> inorderTraversal(TreeNode root) {
            List<Integer> list = new ArrayList<Integer>();
            put(root, list);
            return list;
        }
        
        private void put(TreeNode node, List<Integer> list){
            if(node==null)
                return;
            put(node.left, list);
            list.add(node.val);
            put(node.right, list);
        }
    

      

    Iteration

        public List<Integer> inorderTraversal(TreeNode root) {
            List<Integer> list = new LinkedList<>();
            Stack<TreeNode> stk = new Stack<>();
            while(root!=null || !stk.isEmpty()){
                while(root!=null){
                    stk.push(root);
                    root=root.left;
                }
                list.add(stk.peek().val);
                root = stk.pop().right;
            }
            return list;
        }
    

      

    Complexity

    Time complexity : O(n)

    Space complexity : O(n)

     More:【目录】LeetCode Java实现

  • 相关阅读:
    asp.net读取/导入project(mpp)文件
    hdu2103
    hdu2100(大数加)
    hdu1406
    hdu1249
    hdu1038
    hdu2565
    hdu1203
    zoj3501
    hdu2102
  • 原文地址:https://www.cnblogs.com/yongh/p/11757040.html
Copyright © 2011-2022 走看看