zoukankan      html  css  js  c++  java
  • Leetcode: Binary Tree Inorder Transversal

    Given a binary tree, return the inorder traversal of its nodes' values.
    
    For example:
    Given binary tree {1,#,2,3},
       1
        
         2
        /
       3
    return [1,3,2].
    
    Note: Recursive solution is trivial, could you do it iteratively?

    recursive 方法:

     1 /**
     2  * Definition for binary tree
     3  * public class TreeNode {
     4  *     int val;
     5  *     TreeNode left;
     6  *     TreeNode right;
     7  *     TreeNode(int x) { val = x; }
     8  * }
     9  */
    10 public class Solution {
    11     public List<Integer> inorderTraversal(TreeNode root) {
    12         ArrayList<Integer> res = new ArrayList<Integer>();
    13         if (root == null) return res;
    14         helper(root, res);
    15         return res;
    16     }
    17     
    18     public void helper(TreeNode root, ArrayList<Integer> res) {
    19         if (root == null) {
    20             return;
    21         }
    22         helper(root.left, res);
    23         res.add(root.val);
    24         helper(root.right, res);
    25     }
    26 }

    Iterative method: 参考了一下网上的思路,其实就是用一个栈来模拟递归的过程。所以算法时间复杂度也是O(n),空间复杂度是栈的大小O(logn)。

     1 /**
     2  * Definition for a binary tree node.
     3  * public class TreeNode {
     4  *     int val;
     5  *     TreeNode left;
     6  *     TreeNode right;
     7  *     TreeNode(int x) { val = x; }
     8  * }
     9  */
    10 public class Solution {
    11     public List<Integer> inorderTraversal(TreeNode root) {
    12         List<Integer> res = new ArrayList<>();
    13         Stack<TreeNode> stack = new Stack<>();
    14         TreeNode p = root;
    15         while (p!=null || !stack.isEmpty()) {
    16             if (p != null) {
    17                 stack.push(p);
    18                 p = p.left;
    19             }
    20             else {
    21                 TreeNode node = stack.pop();
    22                 res.add(node.val);
    23                 p = node.right;
    24             }
    25         }
    26         return res;
    27     }
    28 }
  • 相关阅读:
    tomcat配置数据源
    Spring 配置详解
    典型的软件开发模型
    600字让你读懂Git
    JVM的自愈能力
    Maven的pom.xml文件详解
    如何使用Log4j
    掌握jQuery插件开发,这篇文章就够了
    CSS Gradient详解
    CSS Transition
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/3972139.html
Copyright © 2011-2022 走看看