鏈接力扣513-找樹左下角的值
思路
class Solution {
public int findBottomLeftValue(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
int res = 0;
while(!queue.isEmpty()){
int size = queue.size();
for(int i = 0; i < size; i++){
TreeNode node = queue.poll();
if(i == 0) res = node.val;
if(node.left != null) queue.offer(node.left);
if(node.right != null) queue.offer(node.right);
}
}
return res;
}
}
鏈接力扣112-路徑總和
思路文章來源:http://www.zghlxwxcb.cn/news/detail-624555.html
class Solution {
public boolean hasPathSum(TreeNode root, int targetSum) {
// 用前序遍歷
if(root == null) return false;
if(root.left == null && root.right == null) return targetSum == root.val;
// 求兩側(cè)分支的路徑和
return hasPathSum(root.left, targetSum - root.val) || hasPathSum(root.right, targetSum - root.val);
}
}
鏈接力扣106-從中序與后序遍歷序列構(gòu)造二叉樹
思路文章來源地址http://www.zghlxwxcb.cn/news/detail-624555.html
// 重點(diǎn)是:左閉右開的原則,以及子樹長度
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 getRoot(inorder,0,inorder.length,postorder,0,postorder.length);
}
public TreeNode getRoot(int[] inorder, int inStart,int inEnd,int[] postorder,int postStart,int postEnd){
// 參數(shù)里的范圍都是前閉后開,不是左閉右開,則無法返回樹
if(inStart >= inEnd || postStart >= postEnd) return null;
// 獲取中序中的根節(jié)點(diǎn)值;
int index = map.get(postorder[postEnd - 1]);
TreeNode root = new TreeNode(inorder[index]);
// 求出左樹的長度
int lenOfLeft = index - inStart;
// 根據(jù)左閉右開,來建立左子樹、右子樹
root.left = getRoot(inorder,inStart,index, postorder,postStart,postStart + lenOfLeft);
root.right = getRoot(inorder,index + 1, inEnd, postorder,postStart + lenOfLeft,postEnd - 1);
// root.right = getRoot(inorder,index + 1, inEnd, postorder,postStart + index,postEnd - 1);
return root;
}
}
到了這里,關(guān)于【算法第十五天7.29】513.找樹左下角的值 112. 路徑總和 106.從中序與后序遍歷序列構(gòu)造二叉樹的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!