257. Binary Tree Paths
来源:互联网 发布:2017剑灵人男捏脸数据 编辑:程序博客网 时间:2024/05/22 13:50
Problem:
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”]
Analysis:
简单的二叉树遍历,遍历的过程中记录之前的路径,一旦遍历到叶子节点便将该路径加入结果中。
Answer:
// 未完成的用栈实现DFS代码/** * 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> result=new LinkedList<String>(); if(root==null) return result; Stack<Integer> stack =new Stack<Integer>(); stack.add(root); String path=root; while(!stack.empty()){ TreeNode node = stack.pop(); if(node == root) path=path +'->'+node; if(node.left ==null && node.right ==null) path = path + node; else if(node.left!=null) } }}
// 已完成的基于递归思想实现DFS的代码/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { List<String> result=new LinkedList<String>(); public List<String> binaryTreePaths(TreeNode root) { if(root==null) return result; else list_path(root,String.valueOf(root.val)); return result; } private void list_path(TreeNode root,String path){ if(root.left==null&&root.right==null){ result.add(path); } if(root.left!=null){ list_path(root.left,path+"->"+root.left.val); } if(root.right!=null){ list_path(root.right,path+"->"+root.right.val); } }}
0 0
- 257. Binary Tree Paths
- 257. Binary Tree Paths
- 257. Binary Tree Paths
- 257. Binary Tree Paths
- 257. Binary Tree Paths
- 257. Binary Tree Paths
- 257. Binary Tree Paths
- 257. Binary Tree Paths
- 257. Binary Tree Paths
- 257. Binary Tree Paths
- 257. Binary Tree Paths
- 257. Binary Tree Paths
- 257. Binary Tree Paths
- 257. Binary Tree Paths
- 257. Binary Tree Paths
- 257. Binary Tree Paths
- 257. Binary Tree Paths
- 257. Binary Tree Paths
- Android 异步消息处理机制 让你深入理解 Looper、Handler、Message三者关系
- 计算机视觉:让冰冷的机器看懂多彩的世界
- 给虚拟表添加id(给视图加个id)
- 杂文_语录
- missing ios distribution signing identity xxx, xcode can request one for you
- 257. Binary Tree Paths
- UIWebView 与 JS 交互(1):Objective-C 调用 Javascript
- Sublime Text3 绝对神器(安装、配置)
- 浅析android应用增量升级
- web.xml配置文件说明
- 堆和栈的区别(转过无数次的文章)
- php调用java写的webservices提示Uncaught SoapFault exception: [HTTP] Not Found
- 自学Python之 基础语法
- yarrAdetroSdetatoRnimuminiMdniF.153