zoukankan      html  css  js  c++  java
  • Leetcode480-Binary Tree Paths-Easy

    480. Binary Tree Paths

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

    Example

    Example 1:

    Input:
    
       1
     /   
    2     3
     
      5
    
    Output:
    
    
    [
      "1->2->5",
      "1->3"
    ]
    

    Example 2:

    Input:
    
       1
     /   
    2     
     
    
    Output:
    
    
    [
      "1->2"
    ]

    注意:

    因为题目的output格式 "1 -> 2",(有箭头),所以用String来存储每一个path。

    递归法代码:

    /**
     * Definition of TreeNode:
     * public class TreeNode {
     *     public int val;
     *     public TreeNode left, right;
     *     public TreeNode(int val) {
     *         this.val = val;
     *         this.left = this.right = null;
     *     }
     * }
     */
    
    public class Solution {
        /**
         * @param root: the root of the binary tree
         * @return: all root-to-leaf paths
         */
        ArrayList<String> result;
        
        public List<String> binaryTreePaths(TreeNode root) {
            result = new ArrayList<String>();
            if (root == null) {
                return result;
            }
             
            String path = String.valueOf(root.val);
            helper(root, path);
            return result;
        }
        public void helper(TreeNode root, String path) {
            
            if (root.left == null && root.right == null) {
                result.add(path);
                return;
            }
            
            if (root.left != null) {
                helper(root.left, path + "->" + String.valueOf(root.left.val));
            }
            
            if (root.right != null) {
                helper(root.right, path + "->" + String.valueOf(root.right.val));
            }
        }    
    }
  • 相关阅读:
    git安装和使用
    GitHub入门
    jmeter入门
    this关键字
    ES6函数
    代码雨
    this指向练习题
    a标签阻止默认跳转行为事件
    模板引擎的应用
    面向对象
  • 原文地址:https://www.cnblogs.com/Jessiezyr/p/10661656.html
Copyright © 2011-2022 走看看