zoukankan      html  css  js  c++  java
  • 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].

     

    Java代码  收藏代码
    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.         dfs(root, res);  
    14.         return res;  
    15.     }  
    16.   
    17.     private void dfs(TreeNode root, List<Integer> res) {  
    18.         if (root != null) {  
    19.             dfs(root.left, res);  
    20.             res.add(root.val);  
    21.             dfs(root.right, res);  
    22.         }  
    23.     }  
    24. }  

     

    Java代码  收藏代码
    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.         if (root == null) {  
    14.             return res;  
    15.         }  
    16.         LinkedList<TreeNode> stack = new LinkedList<>();  
    17.         while (root!=null || !stack.isEmpty()) {  
    18.             if (root!=null) {  
    19.                 stack.push(root);  
    20.                 root = root.left;  
    21.             } else {  
    22.                 root = stack.pop();  
    23.                 res.add(root.val);  
    24.                 root = root.right;  
    25.             }  
    26.         }  
    27.         return res;  
    28.     }  
    29. }  

    http://hcx2013.iteye.com/blog/2230218

  • 相关阅读:
    python 获取在线视频时长,不下载视频
    python treeview 多线程下表格插入速度慢解决方法
    c#操作magick,magick.net
    油猴脚本-Tampermonkey-淘宝dsr过滤器(过滤非3红商品)
    python 基础小坑 0==False is True
    pyd 编译,简单命令cythonize
    python 调用Tesseract,dll模式,无需安装,绿色版
    list与set的查询效率,大量数据查询匹配,必须选set
    selenium 页面加载慢,超时的解决方案
    selenium 不打印chromedriver的日志信息
  • 原文地址:https://www.cnblogs.com/softidea/p/4678973.html
Copyright © 2011-2022 走看看