zoukankan      html  css  js  c++  java
  • leetcode -- Binary Tree Inorder Traversal

    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 Version

     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 ArrayList<Integer> inorderTraversal(TreeNode root) {
    12         // Start typing your Java solution below
    13         // DO NOT write main() function
    14         ArrayList<Integer> result = new ArrayList<Integer>();
    15         if(root == null){
    16             return result;
    17         }
    18         
    19         if(root.left != null){
    20             result.addAll(inorderTraversal(root.left));
    21         }
    22         result.add(root.val);
    23         if(root.right != null){
    24             result.addAll(inorderTraversal(root.right));
    25         }
    26         return result;
    27     }
    28 }

     Iterative Version

     1 public  ArrayList<Integer> inorderTraversal(TreeNode root) {
     2             // Start typing your Java solution below
     3             // DO NOT write main() function
     4             ArrayList<Integer> res = new ArrayList<Integer>();
     5             if(root==null) return res;
     6             
     7             Stack<TreeNode> s = new Stack<TreeNode>();
     8             TreeNode cur = root;
     9             while(!s.isEmpty()||cur!=null){
    10                 if(cur!=null){
    11                     s.push(cur); 
    12                     cur=cur.left;
    13                 }else{
    14                     cur=s.pop();
    15                     res.add(cur.val);
    16                     cur=cur.right;
    17                 }
    18             }
    19             return res;
    20         }

    复杂度:时间O(n),空间O(logn)

    Morris 算法见如下链接

    http://gongxuns.blogspot.com/2012/12/leetcodebinary-tree-inorder-traversal.html

  • 相关阅读:
    JS调用App方法及App调用JS方法
    提升用户体验之 选用合适的鼠标光标
    js仿QQ拖拽删除
    Linux下安装 mongodb
    QQ分享-定制分享卡片
    js判断浏览器语言实现网站国际化
    js复制内容到剪切板
    为什么会有堆内存和栈内存之分
    Avro实现RPC
    zookeeper学习day01
  • 原文地址:https://www.cnblogs.com/feiling/p/3256607.html
Copyright © 2011-2022 走看看