• 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 }
  • 相关阅读:
    用CSS3实现上下左右箭头
    让input框只能输入数字
    给内联元素设置宽高的几种方式
    当文本溢出包含的元素时加省略号之text-overflow
    通过box盒子模型给元素内容设置居中
    CSS3中的字体rem
    封装一个取消事件冒泡的方法
    HTML5 web workes实现多线程
    通过imeMode禁用键盘只能输入数字
    jquery的children方法和css3选择器配合使用
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/3972139.html
Copyright © 2020-2023  润新知