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

  • 相关阅读:
    C#库
    大话设计模式--简单工厂模式
    weka平台下手动造.arff的数据
    NIM博弈的必胜取法
    求一个全排列函数: 如p([1,2,3])输出:[123],[132],[213],[231],[312],[321]. 求一个组合函数 如p([1,2,3])输出:[1],[2],[3],[1,2],[2,3],[1,3],[1,2,3]
    哥德巴赫猜想
    C#格式化输出
    meta文件里指定资源
    chromatic aberration
    uber shader
  • 原文地址:https://www.cnblogs.com/softidea/p/4678973.html
Copyright © 2011-2022 走看看