社区微信群开通啦,扫一扫抢先加入社区官方微信群
社区微信群
这个专栏 我将分享每日做的算法题的解题思路 秋招加油!
这是第十六天 !!
题目
AC代码
class Solution {
public TreeNode pruneTree(TreeNode root) {
if(root == null){
return null;
}
root.left = pruneTree(root.left);
root.right = pruneTree(root.right);
if(root.val == 0 && root.left == null && root.right == null){
return null;
}
return root;
}
}
递归 树相关的题目首先考虑用递归解决。确定边界即可。
题目
AC代码
public class Codec {
public String serialize(TreeNode root) {
return rserialize(root, "");
}
public TreeNode deserialize(String data) {
String[] dataArray = data.split(",");
List<String> dataList = new LinkedList<String>(Arrays.asList(dataArray));
return rdeserialize(dataList);
}
public String rserialize(TreeNode root, String str) {
if (root == null) {
str += "None,";
} else {
str += str.valueOf(root.val) + ",";
str = rserialize(root.left, str);
str = rserialize(root.right, str);
}
return str;
}
public TreeNode rdeserialize(List<String> dataList) {
if (dataList.get(0).equals("None")) {
dataList.remove(0);
return null;
}
TreeNode root = new TreeNode(Integer.valueOf(dataList.get(0)));
dataList.remove(0);
root.left = rdeserialize(dataList);
root.right = rdeserialize(dataList);
return root;
}
}
深度优先搜索
题目
AC代码
class Solution {
public int sumNumbers(TreeNode root) {
return dfs(root, 0);
}
public int dfs(TreeNode root, int prevSum) {
if (root == null) {
return 0;
}
int sum = prevSum * 10 + root.val;
if (root.left == null && root.right == null) {
return sum;
} else {
return dfs(root.left, sum) + dfs(root.right, sum);
}
}
}
深度优先搜索
春去夏日长,莫负好时光。
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!