1.找树左下角的值
思路:层序遍历迭代法;只需要记录最后一行第一个节点的数值就可以了
注意:使用queue
解法:
public int findBottomLeftValue(TreeNode root){
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
int result = 0;
while (!queue.isEmpty()){
int size = queue.size();
for (int i = 0; i < size; i++) {
TreeNode node = queue.poll();
// 每次都记录第一个值,直到最后一行
if (i == 0)
result = node.val;
if (node.left != null)
queue.offer(node.left);
if (node.right != null)
queue.offer(node.right);
}
}
return result;
}
2.路径总和
思路:递归+回溯;
注意:1.让计数器count初始为目标和,去做递减最后判断是否为0
2.递归函数什么时候需要返回值?什么时候不需要返回值?这里总结如下三点:
如果需要搜索整棵二叉树且不用处理递归返回值,递归函数就不要返回值。(113.路径总和ii)
如果需要搜索整棵二叉树且需要处理递归返回值,递归函数就需要返回值。
如果要搜索其中一条符合条件的路径,那么递归一定需要返回值,因为遇到符合条件的路径了就要及时返回。(本题的情况)
解法:
public boolean hasPathSum(TreeNode root, int targetsum) {
// 终止条件1
if (root == null)
return false;
targetsum -= root.val;
// 终止条件2 判断是否为叶子结点
if (root.left == null && root.right == null)
return targetsum == 0;
// 终止条件3 判断左右子树
if (root.left != null){
boolean left = hasPathSum(root.left, targetsum);
if (left){
return true;
}
}
if (root.right != null){
boolean right = hasPathSum(root.right, targetsum);
if (right) {
return true;
}
}
//
return false;
}
3.路径总和II
思路:还是递归+回溯
注意:区别于上题,这里是返回所有符合要求的路径,所以子函数不需要有返回值
解法:
class Solution {
// 定义全局变量
LinkedList<Integer> path;
List<List<Integer>> result;
public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
result = new LinkedList<>();
path = new LinkedList<>();
travesal(root, targetSum);
return result;
}
private void travesal(TreeNode root, int targetSum) {
// 前序遍历, 先offer节点值
if (root == null)return;
path.offer(root.val);
targetSum -= root.val;
// 判断是否为叶子结点 且符合要求的值 是的话就加入到result中
if (root.left == null && root.right == null && targetSum == 0)
result.add(new ArrayList<>(path));
travesal(root.left, targetSum);
travesal(root.right, targetSum);
path.removeLast(); //回溯
}
}
4.从中序和后序遍历序列构造二叉树
思路:
第一步:如果数组大小为零的话,说明是空节点了。
第二步:如果不为空,那么取后序数组最后一个元素作为节点元素。
第三步:找到后序数组最后一个元素在中序数组的位置,作为切割点
第四步:先切割中序数组,切成中序左数组和中序右数组
第五步:后切割后序数组,根据中序左数组来切割后序左数组和后序右数组
第六步:递归处理左区间和右区间
注意:
中序数组大小一定是和后序数组的大小相同的
务必注意递归处理左右区间时的索引值
class Solution {
Map<Integer, Integer> map; // 方便根据数值查找位置
public TreeNode buildTree(int[] inorder, int[] postorder) {
map = new HashMap<>();
for (int i = 0; i < inorder.length; i++) {
map.put(inorder[i], i);
}
return findNode(inorder, 0, inorder.length, postorder, 0, postorder.length);
}
private TreeNode findNode(int[] inorder, int inBegin, int inEnd, int[] postorder, int postBegin, int postEnd) {
if (inBegin >= inEnd || postBegin >= postEnd)
return null;
int rootIndex = map.get(postorder[postEnd - 1]);
TreeNode root = new TreeNode(inorder[rootIndex]);
int len1 = rootIndex - inBegin;
root.left = findNode(inorder, inBegin, rootIndex,
postorder, postBegin, postBegin + len1);
// 后序数组的最后一个元素不要
root.right = findNode(inorder, rootIndex + 1, inEnd,
postorder, postBegin + len1, postEnd - 1);
return root;
}
}