zoukankan      html  css  js  c++  java
  • 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);
        }
    
    }
    

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

  • 相关阅读:
    多姿多彩的线程
    字典操作
    字符串语法
    购物车
    列表常用语法
    整数划分问题
    计算N的阶层
    判断是否是素数
    快速排序
    冒泡排序
  • 原文地址:https://www.cnblogs.com/optor/p/8727369.html
Copyright © 2011-2022 走看看