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 }
  • 相关阅读:
    2013 HIT 春季校赛C题
    2013610 四省赛
    [BZOJ] 1441 Min
    移植中Makefile学习 关键字理解
    Emgu 学习之HelloWorld
    XML 基本概念和XPath选择
    AI 资源帖
    c语言 static
    Linux watch命令 实时监测命令的运行结果(转)
    ctags 注意点
  • 原文地址:https://www.cnblogs.com/wangnanabuaa/p/4993414.html
Copyright © 2011-2022 走看看