本文主要是介绍leetcode257_二叉树所有路径,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> result = new ArrayList();
if(root==null) return result;
List<Integer> paths = new ArrayList();
dfs(root, paths, result);
return result;
}
private void dfs(TreeNode root, List<Integer> paths, List<String> result) {
paths.add(root.val);
if(root.left == null && root.right == null) {
StringBuilder sb = new StringBuilder();
for(int i = 0; i < paths.size()-1;i++) {
sb.append(paths.get(i)).append("->");
}
sb.append(paths.get(paths.size()-1));
result.add(sb.toString());
}
if(root.left != null) {
dfs(root.left, paths, result);
paths.remove(paths.size()-1);
}
if(root.right != null) {
dfs(root.right, paths, result);
paths.remove(paths.size()-1);
}
return;
}
}
这篇关于leetcode257_二叉树所有路径的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!