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

  • 相关阅读:
    linux 声音大小调整的命令
    Linux下cron的使用
    MySql中添加用户,新建数据库,用户授权,删除用户,修改密码
    yii 删除内容时增加ajax提示
    git 忽略权限
    yii CGridView colum 链接
    yii cgridview 对生成的数据进行分页
    yii cgridview 默认的筛选如何做成选择框
    db2 Reorgchk:重组检查,是否需要重组
    Linux 下文件
  • 原文地址:https://www.cnblogs.com/softidea/p/4678973.html
Copyright © 2011-2022 走看看