leetcode记录 257. Binary Tree Paths
来源:互联网 发布:js div左右滑动效果 编辑:程序博客网 时间:2024/06/06 17:29
自己的思路:分析还是主要考察二叉树的遍历,遍历的时候判断是否为叶子节点,遍历的同时记录路径上值,如果为叶子节点那么输出路径。
路径上的值采用list来存储,有子结点的话,加入list,跳到其他节点(右节点)时候,删除list最后一个节点,就说当该节点被遍历过之后从path中删除该节点。
/** * 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<Integer> path = new ArrayList<Integer>(); List<String> rslt = new ArrayList<String>(); if(root==null) return rslt; treeTraverse(root,path,rslt); return rslt; } public void treeTraverse(TreeNode root,List<Integer> path,List<String> rslt){ if(root!=null) path.add(root.val); if(root.left!=null){ treeTraverse(root.left,path,rslt); } if(root.right!=null){ treeTraverse(root.right,path,rslt); } if(root.left==null&&root.right==null){ String entry = ""; for(int i=0;i<path.size();i++){ if(i!=0) entry+="->"; entry+=path.get(i); } rslt.add(entry); } path.remove(path.size()-1); }}
其实根本都不用专门的一个list来记录路径,因为它是递归的可以直接利用递归和栈是等价的原理来做:
/** * 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> res = new ArrayList<String>(); if (root == null){ return res; } return getPaths (root, "", res); } public List<String> getPaths(TreeNode root, String str, List<String> res){ if (root.left == null && root.right == null){ if (str.equals("")){ str += root.val; } else { str += "->"+root.val; } res.add (str); return res; } if (str.equals("")){ str += root.val; } else { str += "->"+root.val; } if (root.left != null){ getPaths (root.left, str, res); } if (root.right != null){ getPaths (root.right, str, res); } return res; }}以上路径保存在str中。
0 0
- leetcode记录 257. Binary Tree Paths
- [leetcode] 257. Binary Tree Paths
- 257. Binary Tree Paths LeetCode
- 【LeetCode】257. Binary Tree Paths
- LeetCode 257. Binary Tree Paths
- LeetCode *** 257. Binary Tree Paths
- leetcode 257. Binary Tree Paths
- LeetCode 257. Binary Tree Paths
- Leetcode 257. Binary Tree Paths
- LeetCode-257.Binary Tree Paths
- 【leetcode】257. Binary Tree Paths
- [Leetcode]257. Binary Tree Paths
- LeetCode - 257. Binary Tree Paths
- LeetCode 257. Binary Tree Paths
- [leetcode] 257. Binary Tree Paths
- LeetCode 257. Binary Tree Paths
- 257.[Leetcode]Binary Tree Paths
- LeetCode 257. Binary Tree Paths
- getsupportfragmentmanager()找不到这个方法
- SVN误删根目录导致无法安装无法卸载无法更改办法( invalid device K:\)
- STM32F4板子使用LWIP进行组播收发数据的完整过程,附代码
- 【代码笔记】iOS-评分系统(小星星)
- SQLSERVER2008R2创建分区表、转换分区表、交换数据
- leetcode记录 257. Binary Tree Paths
- 推荐一个非常有用的WordPress插件:WP2CSDNBlog
- Android Material Design之Toolbar与Palette实践
- GCD基本用法
- android模拟器启动不了,出现乱码提示
- service工程报错解决方案
- 机器学习 条件随机场CRF
- Andriod Fragment---给Activity添加一个Fragment
- 浅谈iOS中MVVM的架构设计与团队协作