zoukankan      html  css  js  c++  java
  • 257. 二叉树的所有路径

    BFS解,时间O(n^2),空间O(n^2)

     1     public List<String> binaryTreePaths(TreeNode root) {
     2         List<String> paths = new ArrayList<String>();
     3         if(root==null) return paths;
     4         Queue<TreeNode> queue1 = new LinkedList<TreeNode>();
     5         Queue<String> queue2 = new LinkedList<String>();
     6         queue1.add(root);
     7         queue2.add(Integer.toString(root.val));
     8         while(!queue1.isEmpty()){
     9             TreeNode temp = queue1.poll();
    10             String path = queue2.poll();            
    11             if(temp.left==null && temp.right==null){
    12                 paths.add(path);
    13                 continue;
    14             }
    15             if(temp.left!=null){
    16                 queue1.add(temp.left);
    17                 queue2.add(new StringBuilder(path).append("->"+temp.left.val).toString());
    18             }
    19             if(temp.right!=null){
    20                 queue1.add(temp.right);
    21                 queue2.add(new StringBuilder(path).append("->"+temp.right.val).toString());
    22             }
    23         }
    24         return paths;
    25     }
    争取早日不再是一只菜鸡
  • 相关阅读:
    Hbase表的管理
    Hbase指定规则扫描表
    vim配置
    caogao
    go on shell
    实习总结
    shell 脚本
    hadoop实战
    awk使用
    java reflect
  • 原文地址:https://www.cnblogs.com/jchen104/p/14714009.html
Copyright © 2011-2022 走看看