问题描述
所给代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
}
}
代码演示
/**
*执行用时 : 3 ms, 在Binary Tree Paths的Java提交中击败了98.30% 的用户
*内存消耗 : 35.8 MB, 在Binary Tree Paths的Java提交中击败了98.51% 的用户
*
*/
class Solution {
List<String> list = new ArrayList<String>();
String str = "";
public List<String> binaryTreePaths(TreeNode root) {
dfs(root, str);
return list;
}
public void dfs(TreeNode root, String str) {
if(root==null) { return; }
str += root.val;
if(root.left != null || root.right != null) { str += "->"; } // 判断该结点是否为根节点 若为根节点,则不添加"->",若左子树或右子树不为空,则添加"->"
if(root.left == null && root.right == null) { list.add(str); } // 判断该结点是否为根节点,是的话就将字符串添加到list集合中.
dfs(root.left, str);
dfs(root.right, str);
}
}
自己所写(错误演示,仅供自己反思)
class Solution {
List<String> list = new ArrayList<String>();
public List<String> binaryTreePaths(TreeNode root) {
if(root!=null) {
sb.append(root.val);
if(root.left != null || root.right != null) { sb.append("->"); }
binaryTreePaths(root.left);
if(root.left == null && root.right == null) {list.add(sb.toString());sb.delete(sb.length()-1,sb.length());}
// else{ sb.delete(sb.length()-1,sb.length());}
binaryTreePaths(root.right);
// if(root.left == null && root.right == null) {list.add(sb.toString());sb.delete(0, sb.length());}
//else {sb.delete(3, sb.length());}
}
return list;
}
}
自己最终停留在了这里…受之前遍历的影响,光想着遍历树了,结果无法实现往上回滚的操作.
看了别人代码之后反思.
首先对于自己的StringBuilder的使用就是错误.因为它增加了操作难度.需要对已存字符串进行删除操作.
其次就是通过参数的传递来实现无需回滚的想法,参数通过递归传到里面,并不会更改之前的字符串.而是保持不变.这里就很巧妙!