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

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

  • 相关阅读:
    bzoj2599
    在Linux下配置jdk的环境变量
    liunx 命令大全
    Liunx下如何使用kettle
    Liunx 解压篇
    Linux下安装MySQL-5.7
    Linux文件权限查看及修改命令chmod,chown
    spring 驱动模式
    Struts2标签之Checkbox
    spring 注解的优点缺点
  • 原文地址:https://www.cnblogs.com/optor/p/8727369.html
Copyright © 2011-2022 走看看