美文网首页
257. Binary Tree Paths

257. Binary Tree Paths

作者: lqsss | 来源:发表于2018-02-01 18:49 被阅读0次

    题目和思路

    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"]
    

    简单的递归

    代码

    package tree;
    
    import java.util.ArrayList;
    import java.util.List;
    
    /**
     * Created by liqiushi on 2018/2/1.
     */
    public class BinaryTreePaths {
        public List<String> binaryTreePaths(TreeNode root) {
            List<String> resultList = new ArrayList<>();
            if(root == null){
                return resultList;
            }
            searchBst(root, "", resultList);
            return resultList;
        }
    
        private void searchBst(TreeNode root, String path, List<String> resultList) {
            if (root.left == null && root.right == null) {
                resultList.add(path + root.val );
            }
            if (root.left != null) {
                searchBst(root.left, path + root.val + "->", resultList);
            }
            if (root.right != null) {
                searchBst(root.right, path + root.val + "->", resultList);
            }
        }
    }
    
    

    相关文章

      网友评论

          本文标题:257. Binary Tree Paths

          本文链接:https://www.haomeiwen.com/subject/gkhjzxtx.html