zoukankan      html  css  js  c++  java
  • 257. Binary Tree Paths java solutions

    Given a binary tree, return all root-to-leaf paths.

    For example, given the following binary tree:

       1
     /   
    2     3
     
      5
    

    All root-to-leaf paths are:

    ["1->2->5", "1->3"]

    Credits:
    Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

    Subscribe to see which companies asked this question

     
     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     List<String> ans = new ArrayList<String>();
    12     public List<String> binaryTreePaths(TreeNode root) {
    13         if(root == null) return ans;
    14         String tmp = "" + root.val;
    15         DFS(ans,root,tmp);
    16         return ans;
    17     }
    18     
    19     public void DFS(List<String> ans, TreeNode node, String tmp){
    20         if(node.left == null && node.right == null){
    21             ans.add(tmp);
    22             return;
    23         }
    24         if(node.left != null) DFS(ans,node.left,tmp+"->"+node.left.val);
    25         if(node.right != null) DFS(ans,node.right,tmp+"->"+node.right.val);
    26     }
    27 }

    用递归即可。

  • 相关阅读:
    rwkj 1337
    poj 1002
    map
    vector
    sort排序
    sort函数
    poj 2945
    poj2388
    rwkj 1422搜索(素数环)
    poj2503
  • 原文地址:https://www.cnblogs.com/guoguolan/p/5614950.html
Copyright © 2011-2022 走看看