[LeetCode] Binary Tree Paths
生活随笔
收集整理的這篇文章主要介紹了
[LeetCode] Binary Tree Paths
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Given a binary tree, return all root-to-leaf paths.
For example, given the following binary tree:
1/ \ 2 3\ 5All root-to-leaf paths are:
[“1->2->5”, “1->3”]
解題思路
先序遍歷,遞歸的過程中保存路徑,遇到葉子節點時將路徑加入結果集。
實現代碼
Java:
// Runtime: 3 ms /*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode(int x) { val = x; }* }*/ public class Solution {private List<String> paths = new ArrayList<String>();public List<String> binaryTreePaths(TreeNode root) {if (root != null) {traverse(root, String.valueOf(root.val));}return paths;}private void traverse(TreeNode root, String path) {if (root.left == null && root.right == null) {paths.add(path);}if (root.left != null) {traverse(root.left, path + "->" + root.left.val);}if (root.right != null) {traverse(root.right, path + "->" + root.right.val);}} }總結
以上是生活随笔為你收集整理的[LeetCode] Binary Tree Paths的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C# 读取在存储过程多结果集
- 下一篇: HTTP错误 大全