1.二叉树的右视图 力扣199
因为是从上到下的写入list,所以只需要把每层的最后一个节点写入res即可,用简化版的层序遍历即可
class Solution {
Queue<TreeNode> queue = new LinkedList<>();
List<Integer> res = new ArrayList<>();
public List<Integer> rightSideView(TreeNode root) {
if (root == null) return res;
queue.offer(root);
while (!queue.isEmpty()) {
int n = queue.size();
for (int i = 0;i < n;i++) {
TreeNode node = queue.poll();
if (node.left != null) {
queue.offer(node.left);
}
if (node.right != null) {
queue.offer(node.right);
}
if (i == n - 1) {
res.add(node.val);
}
}
}
return res;
}
}
2.完全二叉树节点个数 :222
跟二叉树最大深度问题差不多,都是利用递归原理来进行求个数问题
class Solution {
public int countNodes(TreeNode root) {
if (root == null) return 0;
return countNodes(root.left) + countNodes(root.right) + 1;
}
}
3.翻转二叉树 226
从头节点开始,开始交换左右子树,利用递归
class Solution {
public TreeNode invertTree(TreeNode root) {
if (root == null) return null;
TreeNode left = invertTree(root.left);
TreeNode right = invertTree(root.right);
root.left = right;
root.right = left;
return root;
}
}
4.二叉树的所有路径 257
首先确定是深度优先搜索的思想,dfs中要确定停止条件,那就是左右节点都无时停止搜索。如果节点不为空,就利用递归不断的往path中添加,利用remove完成回溯。在停止搜索时,因为我们要对字符串改变,所以建立线程安全的stringbuffer进行操作。利用循环来加入数字与字符,要单独加入最后一个数字,因为最后没有字符。完成操作后,利用tostring方法在res中填入,最后返回res即可。
class Solution {
List<Integer> path = new ArrayList<>();
List<String> res = new ArrayList<>();
public List<String> binaryTreePaths(TreeNode root) {
if (root == null) return res;
dfs(root);
return res;
}
public void dfs (TreeNode root) {
path.add(root.val);
if (root.left == null && root.right == null) {
StringBuffer sb = new StringBuffer();
for (int i = 0;i < path.size() - 1;i++) {
sb.append(path.get(i)).append("->");
}
sb.append(path.get(path.size() - 1));
res.add(sb.toString());
return;
}
if (root.left != null) {
dfs(root.left);
path.remove(path.size() - 1);
}
if (root.right != null) {
dfs(root.right);
path.remove(path.size() - 1);
}
}
}
5.左子叶之和 404
建立布尔判断是否为叶节点,深度遍历需要分清楚,如果是左节点,如果他是叶节点,就加和,不是就遍历,对于右节点,只要不为空就遍历即可
class Solution {
public int sumOfLeftLeaves(TreeNode root) {
return root == null ? 0 : dfs(root);
}
public int dfs(TreeNode root) {
int ans = 0;
if (root.left != null) {
ans += isye(root.left) ? root.left.val : dfs(root.left);
}
if (root.right != null && !isye(root.right)) {
ans += dfs(root.right);
}
return ans;
}
public boolean isye (TreeNode root) {
return (root.left == null && root.right == null);
}
}