257. Binary Tree Paths

Posted optor

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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);
    }

}

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

以上是关于257. Binary Tree Paths的主要内容,如果未能解决你的问题,请参考以下文章

Java [Leetcode 257]Binary Tree Paths

257. Binary Tree Paths

LeetCode257. Binary Tree Paths 解题报告

257. Binary Tree Paths

257.Binary Tree Paths

257. Binary Tree Paths