257. Binary Tree Paths

2018-02-01  本文已影响0人  lqsss

题目和思路

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);
        }
    }
}

上一篇下一篇

猜你喜欢

热点阅读