513.找树左下角的值
题目链接:513.找树左下角的值
思路:确定递归函数的参数和返回值,树的根节点和最大深度为参数,返回值void。当遇到叶子节点统计最大深度。递归过程中使用回溯。
class Solution {
private int result = 0;
private int maxDepth = -1;
public int findBottomLeftValue(TreeNode root) {
traversal(root,0);
return result;
}
public void traversal(TreeNode root,int depth){
if(root == null)return;
if(root.left == null && root.right == null){
if(depth > maxDepth){
maxDepth = depth;
result = root.val;
}
}
if(root.left!=null){
depth++;
traversal(root.left,depth);
depth--;
}
if(root.right!=null){
depth++;
traversal(root.right,depth);
depth--;
}
}
}
112. 路径总和
题目链接:112. 路径总和
思路:递归函数参数为根节点和计数器记录二叉树一条边之和。当计数器减为0且遍历到叶子节点说明找到目标和。单层递归逻辑是当递归函数返回true时说明找到了合适的路径,立即返回。
class Solution {
public boolean hasPathSum(TreeNode root, int targetSum) {
if(root == null)return false;
if(root.left == null && root.right == null && targetSum == 0){
return true;
}
if(root.left == null && root.right == null && targetSum != 0){
return false;
}
if(root.left!=null){
targetSum -= root.left.val;
if (hasPathSum(root.left,targetSum)){
return true;
}
targetSum += root.left.val;
}
if(root.right!=null){
targetSum -= root.right.val;
if (hasPathSum(root.right,targetSum)){
return true;
}
targetSum += root.right.val;
}
return false;
}
}
113.路径总和ii(后续补充。。)
题目链接:113.路径总和ii
106.从中序与后序遍历序列构造二叉树
题目链接:106.从中序与后序遍历序列构造二叉树
思路:取后序数组最后一个元素作为节点元素。找到后序数组最后一个元素在中序数组的位置,作为切割点。切割中序数组,切成中序左数组和中序右数组 。切割后序数组,切成后序左数组和后序右数组。递归处理左区间和右区间。
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);
}
public 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 lenOfLeft = rootIndex - inBegin;
root.left = findNode(inorder, inBegin, rootIndex,
postorder, postBegin, postBegin + lenOfLeft);
root.right = findNode(inorder, rootIndex + 1, inEnd,
postorder, postBegin + lenOfLeft, postEnd - 1);
return root;
}
}
105.从前序与中序遍历序列构造二叉树(后续补充。。)
题目链接:105.从前序与中序遍历序列构造二叉树