zoukankan      html  css  js  c++  java
  • leetcode-257. Binary Tree Paths

    257. 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"]
    输出所有根节点到叶子节点的路径
    java代码:
    /**
     * 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> answer=new ArrayList<String>();
            if(root!=null)searchBT(root,"",answer);
            return answer;
        }
        private void searchBT(TreeNode root,String path,List<String> answer){//深度优先搜索
    	    if(root.left==null&&root.right==null)answer.add(path+root.val);
    	    if(root.left!=null)searchBT(root.left,path+root.val+"->",answer);
    	    if(root.right!=null)searchBT(root.right,path+root.val+"->",answer);
        }
    }
    

      

  • 相关阅读:
    C++primer习题3.13
    Indesign技巧
    《转载》虚函数在对象中的内存布局
    C++new失败后如何处理
    sizeof的用法
    转载 C++中虚继承防止二义性
    字符串反转
    回文写法
    C++术语
    QT+VS2008
  • 原文地址:https://www.cnblogs.com/lcbg/p/6592106.html
Copyright © 2011-2022 走看看