lintcode-easy-Binary Tree Paths
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了lintcode-easy-Binary Tree Paths相关的知识,希望对你有一定的参考价值。
Given a binary tree, return all root-to-leaf paths.
这道题主要利用一下java的一个特性,String是immutable的对象,不能修改,只能重新生成
/** * 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 */ public List<String> binaryTreePaths(TreeNode root) { // Write your code here List<String> result = new ArrayList<String>(); if(root == null) return result; String str = null; helper(str, result, root); return result; } public void helper(String str, List<String> result, TreeNode root){ if(root.left == null && root.right == null){ if(str == null){ str = String.valueOf(root.val); } else{ str = str + "->" + String.valueOf(root.val); } result.add(str); return; } String new_str = null; if(str == null){ new_str = String.valueOf(root.val); } else{ new_str = str + "->" + String.valueOf(root.val); } if(root.left != null) helper(new_str, result, root.left); if(root.right != null) helper(new_str, result, root.right); return; } }
以上是关于lintcode-easy-Binary Tree Paths的主要内容,如果未能解决你的问题,请参考以下文章
lintcode-easy-Binary Tree Inorder Traversal