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

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

    Given the following binary tree:

       1
     /   
    2     3
     
      5
    

    All root-to-leaf paths are:

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

    解题思路:这道题目应该就是单纯的二叉树遍历,从根节点出发,遍历左右子节点并记录遍历路径,递归调用至叶节点;

     1 /**
     2  * Definition of TreeNode:
     3  * public class TreeNode {
     4  *     public int val;
     5  *     public TreeNode left, right;
     6  *     public TreeNode(int val) {
     7  *         this.val = val;
     8  *         this.left = this.right = null;
     9  *     }
    10  * }
    11  */
    12 public class Solution {
    13   
    14     List<String> res = new ArrayList<String>();
    15     public List<String> binaryTreePaths(TreeNode root) {
    16         // Write your code here
    17         if(root != null) findPaths(root,String.valueOf(root.val));
    18         return res;
    19     }
    20     public void findPaths(TreeNode n,String path){
    21         if(n.left==null && n.right==null)   res.add(path);
    22         if(n.right!=null)   findPaths(n.right,path+"->"+n.right.val);
    23         if(n.left!= null)   findPaths(n.left ,path+"->"+n.left.val);
    24     }
    25 }
  • 相关阅读:
    ASP生成静态文件编码为UTF-8格式的HTML文件
    asp图片化电话号码,避免蜘蛛之类爬走用户隐私
    动态上传多个文件(asp)
    简单测试IIS下的UrlRewrite技术
    mac配置tomcat
    CSS盒子
    CSS
    HTML
    从java到python
    HTTP协议
  • 原文地址:https://www.cnblogs.com/wangnanabuaa/p/4993414.html
Copyright © 2011-2022 走看看