码迷,mamicode.com
首页 > 其他好文 > 详细

257. Binary Tree Paths

时间:2018-04-06 14:00:24      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:blog   sys   .com   ==   source   深度优先遍历   com   arraylist   string   

原题链接: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

标签:blog   sys   .com   ==   source   深度优先遍历   com   arraylist   string   

原文地址:https://www.cnblogs.com/optor/p/8727369.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!