zoukankan      html  css  js  c++  java
  • Leetcode 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"]

    解题思路:

    依然recursion! 用DFS。 关键点:让路径string 伴随着遍历树的点,点到哪里,路径值跟到哪里。


    Java code:

    /**
     * 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> result = new ArrayList<String>();
            if(root == null) { return result; }
            String path = root.val + "";
            getPath(root, result, path);
            return result;
        }
        
        void getPath(TreeNode root, List<String> result, String path) {
            if(root.left == null && root.right == null) {
                result.add(path);
            }
            if(root.left != null) {
                getPath(root.left, result, path+"->"+root.left.val+"");
            }
            if(root.right != null) {
                getPath(root.right, result, path+"->"+root.right.val+"");
            }
        }
    }

    Reference:

    1. http://www.hihuyue.com/hihuyue/codepractise/leetcode/leetcode174-binary-tree-paths 

  • 相关阅读:
    Light Bulb(三分)
    Turn the corner (三分)
    xmu1214: 购物
    Tempter of the Bone(dfs奇偶剪枝)
    Oh, my goddess(bfs)
    nyoj三个水杯(bfs)
    组合数(dfs)
    吝啬的国度(dfs+vector)
    Cube Stacking(并差集深度+结点个数)
    python之socketserver实现并发
  • 原文地址:https://www.cnblogs.com/anne-vista/p/4815090.html
Copyright © 2011-2022 走看看