zoukankan      html  css  js  c++  java
  • 257. Binary Tree Paths

    题目:

    Given a binary tree, return all root-to-leaf paths.

    For example, given the following binary tree:

       1
     /   
    2     3
     
      5
    

    All root-to-leaf paths are:

    ["1->2->5", "1->3"]

    链接: http://leetcode.com/problems/binary-tree-paths/

    题解:

    求Binary Tree所有路径。用Recursive解法会比较容易。逻辑是,假如为current root为leaf node,则在res中加入该节点,返回。否则,递归求解,在左子树和右子树每一个结果中,在String前面insert  root.val + "->"。

    Time Complexity - O(n), Space Complexity - O(n)

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public List<String> binaryTreePaths(TreeNode root) {
            List<String> res = new ArrayList<>();
            if(root == null)
                return res;
            if(root.left == null && root.right == null) {
                res.add(String.valueOf(root.val));
            } else {
                for(String s : binaryTreePaths(root.left)) {
                    res.add(String.valueOf(root.val) + "->" + s);
                } 
                for(String s : binaryTreePaths(root.right)) {
                    res.add(String.valueOf(root.val) + "->" + s);
                } 
            }
                
            return res;
        }
    }

    二刷:

    还是使用了最简单的DFS Recursive解法。更好的解法可能是stack DFS和queue BFS。

    Java: 

    Time Complexity - O(n), Space Complexity - O(n)

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public List<String> binaryTreePaths(TreeNode root) {
            List<String> res = new ArrayList<>();
            if (root == null) {
                return res;
            }
            if (root.left == null && root.right == null) {
                res.add(root.val + "");
                return res;
            }
            List<String> left = binaryTreePaths(root.left);
            List<String> right = binaryTreePaths(root.right);
            for (String s : left) {
                res.add(root.val + "->" + s);
            }
            for (String s : right) {
                res.add(root.val + "->" + s);
            }
            return res;
        }
    }

    三刷:

    完全忘了一刷二刷是怎么写的,直接就用dfs + backtracking了。辅助方法里面用的是in-order traversal。 这里使用了一个List<Integer>来辅助计算Path,否则单独使用一个StringBuilder并不十分方便。

    Java:

    Time Complexity - O(n), Space Complexity - O(n)

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public List<String> binaryTreePaths(TreeNode root) {
            List<String> res = new ArrayList<>();
            List<Integer> path = new ArrayList<>();
            getBinaryTreePaths(res, path, root);
            return res;
        }
        
        private void getBinaryTreePaths(List<String> res, List<Integer> path, TreeNode root) {
            if (root == null) return;
            path.add(root.val);
            if (root.left == null && root.right == null) {
                StringBuilder sb = new StringBuilder();
                for (int val : path) sb.append(val).append("->");
                sb.setLength(sb.length() - 2);
                res.add(sb.toString());
                path.remove(path.size() - 1);
                return;
            }
            getBinaryTreePaths(res, path, root.left);
            getBinaryTreePaths(res, path, root.right);
            path.remove(path.size() - 1);
        }
    }

    Update:

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public List<String> binaryTreePaths(TreeNode root) {
            List<String> res = new ArrayList<>();
            binaryTreePaths(res, new ArrayList<Integer>(), root);
            return res;
        }
        
        private void binaryTreePaths(List<String> res, List<Integer> path, TreeNode root) {
            if (root == null) return;
            path.add(root.val);
            if (root.left == null && root.right == null) {
                StringBuilder sb = new StringBuilder();
                for (int val : path) sb.append(val).append("->");
                sb.setLength(sb.length() - 2);
                res.add(sb.toString());
                path.remove(path.size() - 1);
                return;
            }
            binaryTreePaths(res, path, root.left);
            binaryTreePaths(res, path, root.right);
            path.remove(path.size() - 1);
        }
    }

    写在一个方法里,仿照一刷二刷的dfs:

    这里每次递归都要创建新的ArrayList,并且左右子树都要计算,空间复杂度会比较高。怎么计算清楚,留给下一次了。

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public List<String> binaryTreePaths(TreeNode root) {
            List<String> res = new ArrayList<>();
            if (root == null) return res;
            if (root.left == null && root.right == null) res.add(String.valueOf(root.val));
            
            List<String> left = binaryTreePaths(root.left);
            for (String leftPath :left) res.add(root.val + "->" + leftPath);
            
            List<String> right = binaryTreePaths(root.right);
            for (String rightPath :right) res.add(root.val + "->" + rightPath);
            
            return res;
        }
    }

     

    Reference:

    https://leetcode.com/discuss/55451/clean-solution-accepted-without-helper-recursive-function

    https://leetcode.com/discuss/52072/accepted-java-simple-solution-in-8-lines

    https://leetcode.com/discuss/52020/5-lines-recursive-python

    https://leetcode.com/discuss/65362/my-concise-java-dfs-solution

    https://leetcode.com/discuss/67749/bfs-with-two-queue-java-solution

  • 相关阅读:
    ubuntu中,update,upgrade出现问题总结
    Xshell7连接kali linux(2021.9.13)
    pycharm安装igraph,简单实例(2021.8.21)
    mininet可视化(2021.6.25)
    冷知识:你会搜索信息吗
    论文写作注意事项
    onenote2016怎么自动备份笔记本到本地?
    Cbench、Scapy、sflow、iperf——学习中
    Zookeeper、Docker——学习中
    OpenStack管理、KVM、ClouldSim部署——学习中
  • 原文地址:https://www.cnblogs.com/yrbbest/p/5014959.html
Copyright © 2011-2022 走看看