• 257.Binary Tree Paths


        /*
         * 257.Binary Tree Paths 
         * 2016-6-21 By mingyang 
         * 这个题目吧,刚开始想用backtracking来做,后面看网上都不用回溯,因为可以直接传string这个参数
         * 原理都一样的,而且更简单了。
         */
         public static List<String> binaryTreePaths1(TreeNode root) {
                List<String> res=new ArrayList<String>();
                StringBuffer sb=new StringBuffer();
                if(root==null)
                  return res;
                sb.append(root.val);
                dfs(res,sb,root);
                return res;
            }
            public static void dfs(List<String> res,StringBuffer sb,TreeNode root){
                if(root==null)
                  return;
                if(root.left==null&&root.right==null){
                    res.add(sb.toString());
                    return;
                }
                sb.append("->");
                int k=sb.length();
                //本来不用两个if,因为对于空一定有判断
                if(root.left!=null){
                    sb.append(root.left.val);
                    dfs(res,sb,root.left);
                    sb.setLength(k);
                }
                if(root.right!=null){
                    sb.append(root.right.val);
                    dfs(res,sb,root.right);
                //这里为什么不用delete呢?因为我们以前是for循环,所以需要delete以避免对下一个产生影响
                //这里我们只有右节点就到头了,所以我们只需要结束本层循环就好了
                }
            }
            //网上的代码,不用backtracking
        public List<String> binaryTreePaths(TreeNode root) {
            List<String> res = new ArrayList<String>();
            if (root != null) 
            dfs(root, "", res);
            return res;
        }
        private void dfs(TreeNode root, String path, List<String> res) {
            if (root.left == null && root.right == null) res.add(path + root.val);
            if (root.left != null) dfs(root.left, path + root.val + "->", res);
            if (root.right != null) dfs(root.right, path + root.val + "->", res);
        }
  • 相关阅读:
    12.精益敏捷项目管理——产品协调小组笔记
    打字游戏
    提升权限
    下载者
    SMTP实现发送邮箱2(封装版)
    SMTP实现发送邮箱1
    电子邮件协议详解
    JSON运用在文件
    JSON函数表2
    JSON函数表1
  • 原文地址:https://www.cnblogs.com/zmyvszk/p/5606017.html
Copyright © 2020-2023  润新知