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

    Question:

    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"]

     Analysis:

    问题描述:给出一棵二叉树,给出所有根节点到叶子节点的路径。

    思路一:递归

    Answer:

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        List<String> res = new ArrayList<String>();
        public List<String> binaryTreePaths(TreeNode root) {
            if(root != null)
                findPath(root, Integer.toString(root.val));
            return res;
        }
        
        public void findPath(TreeNode root, String string) {
            // TODO Auto-generated method stub
            if(root.left == null && root.right == null)
                res.add(string);
            if(root.left != null)
                findPath(root.left, string + "->" + Integer.toString(root.left.val));
            if(root.right != null)
                findPath(root.right, string + "->" + Integer.toString(root.right.val));
        }
    }

    思路二:深度优先遍历,用栈保存遍历过的节点。

  • 相关阅读:
    【Linux】sed笔记
    【Linux】nl笔记
    【Kubernetes】架构全图
    【Linux】tar压缩解压缩笔记
    【Docker】初识与应用场景认知
    【Ubuntu】16.04网卡信息配置
    常用枚举类
    mysql生成主键
    eclipse下mybatis-generator-config插件
    tomcat下载镜像地址
  • 原文地址:https://www.cnblogs.com/little-YTMM/p/4844331.html
Copyright © 2011-2022 走看看