zoukankan      html  css  js  c++  java
  • 中序遍历 递归与非递归

     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     
    12     public List<Integer> inorderTraversal(TreeNode root) {
    13         ArrayList<Integer> arr=new ArrayList<Integer>();
    14         if(root==null) return arr;
    15        inorder(root,arr);
    16        return (List)arr;
    17         
    18         
    19     }
    20      public void inorder(TreeNode root,ArrayList<Integer> arr) {
    21         if(root!=null)
    22         {
    23            inorder(root.left,arr);
    24            arr.add(root.val);
    25            inorder(root.right,arr);
    26         }
    27 
    28         
    29         
    30     }
    31 }

    2。非递归

    /**
     * Definition for binary tree
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        
        public List<Integer> inorderTraversal(TreeNode root) {
            ArrayList<Integer> arr=new ArrayList<Integer>();
            if(root==null) return arr;
           Stack<TreeNode> s=new Stack<TreeNode>();
           TreeNode t=root;
           while(!s.isEmpty()||t!=null)
           {
               while(t!=null)
               {
                   s.push(t);
                   t=t.left;
               }
               
               if(s!=null)
               {
                   t=s.pop();
                  arr.add(t.val);
                  t=t.right;
                   
                   
               }
               
               
           }
            
            return arr;
        }
        
    }
  • 相关阅读:
    关于闭包的一些知识
    浏览器解析JavaScript原理(1)
    函数作用域及函数表达式
    jquery
    前端常用插件
    Git及GitHub
    angular框架
    express
    ES6基础
    Node.js相关总结
  • 原文地址:https://www.cnblogs.com/hansongjiang/p/3823052.html
Copyright © 2011-2022 走看看