257. Binary Tree Paths

原题链接:https://leetcode.com/problems/binary-tree-paths/description/
直接走一波深度优先遍历:

import java.util.ArrayList;
import java.util.List;

/**
 * Created by clearbug on 2018/2/26.
 */
public class Solution {

    public static void main(String[] args) {
        Solution s = new Solution();
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.left.right = new TreeNode(5);
        root.right = new TreeNode(3);
        System.out.println(s.binaryTreePaths(root));
    }

    public List<String> binaryTreePaths(TreeNode root) {
        List<String> res = new ArrayList<>();
        dfs(root, new ArrayList<>(), res);
        return res;
    }

    private void dfs(TreeNode root, List<Integer> pathVals, List<String> res) {
        if (root == null) {
            return;
        }
        if (root.left == null && root.right == null) {
            pathVals.add(root.val);
            StringBuilder sb = new StringBuilder();
            for (Integer item : pathVals) {
                sb.append(item + "->");
            }
            res.add(sb.toString().substring(0, sb.length() - 2));
            pathVals.remove(pathVals.size() - 1);
            return;
        }
        pathVals.add(root.val);
        dfs(root.left, pathVals, res);
        dfs(root.right, pathVals, res);
        pathVals.remove(pathVals.size() - 1);
    }

}

不过这道题目我的实现还是写复杂了,提交区有的是简洁高效的代码。。。都怪自己基础不好啊!!!

posted @ 2018-04-06 12:20  optor  阅读(138)  评论(0编辑  收藏  举报