513. 找树左下角的值
class Solution {
int maxDepth = 0;
int res = 0;
public int findBottomLeftValue(TreeNode root) {
//int res = 0;
本题用层序遍历感觉可以
//Deque<TreeNode> deque = new LinkedList<>();
//deque.offer(root);
//
//while (!deque.isEmpty()){
// int size = deque.size();
// res = deque.peek().val;
// while(size-- > 0){
// TreeNode node = deque.poll();
// if(node.left != null) deque.offer(node.left);
// if(node.right != null) deque.offer(node.right);
// }
//}
//return res;
//需要前序遍历,因为要知道当前节点的深度
//思路主要是要记录当前节点的深度,使用一个值记录当前递归遍历到的最深层,当当前节点的深度大于了最深层时,将最深层替换为当前节点的深度,同时更新结果值
preOrderTraversal(root, 1);
return res;
}
void preOrderTraversal(TreeNode root, int depth){
if(root == null){
return;
}
if(depth > maxDepth){
maxDepth = depth;
res = root.val;
}
preOrderTraversal(root.left, depth + 1);
preOrderTraversal(root.right, depth + 1);
}
}
——————————————————————————————————————————
112. 路径总和
class Solution {
int sum = 0;
boolean res = false;
public boolean hasPathSum(TreeNode root, int targetSum) {
preOrderTraversal(root, targetSum);
return res;
}
//前序遍历
void preOrderTraversal(TreeNode root, int targetSum){
if(root == null){
return;
}
sum += root.val;
if(root.right == null && root.left == null){
if(sum == targetSum){
res = true;
}
}
if(root.left != null) {
preOrderTraversal(root.left, targetSum);
sum -= root.left.val;
}
if(root.right != null) {
preOrderTraversal(root.right, targetSum);
sum -= root.right.val;
}
}
}
—————————————————————————————————————————
106. 从中序与后序遍历序列构造二叉树
class Solution {
public TreeNode buildTree(int[] inorder, int[] postorder) {
//拥有中序遍历序列和前后序遍历序列中的任何一个均可构造二叉树
//中序遍历序列主要用来分割左右子树
//本题的思路就是递归去构造二叉树,在每一次的递归体中:递归调用构造左子树、递归调用构造右子树、构造以当前节点为根节点的二叉树
//所以关键就在于怎么从已知的遍历序列中找到每一次当前节点的左右子树的遍历序列
//本题中,有中序和后序遍历序列,后序遍历序列的最后一个元素就是整个树的根节点
//设后序遍历序列的最后一个元素为x,在中序遍历序列找到x的位置,以x为界,左边是左子树序列,右边是右子树序列
//从中序遍历序列中找到左右子树的中序遍历序列后,使用找到的左右子树的中序遍历序列长度去后序遍历序列中分割即可拿到左右子树的后序遍历序列
return buildTreeFunc(inorder, postorder,0, inorder.length, 0, postorder.length);
}
//索引范围为左闭右开
private TreeNode buildTreeFunc(int[] inorder, int[] postorder, int inStart, int inEnd, int postStart, int postEnd){
if(inEnd - inStart < 1){
return null;
}
int rootVal = postorder[postEnd - 1];
int rootInIndex = -1;
for(int i = inStart; i < inEnd; i++){
if(inorder[i] == rootVal){
rootInIndex = i;
break;
}
}
TreeNode root = new TreeNode(inorder[rootInIndex]);
int rightSubTreePostStart = postEnd - (inEnd - rootInIndex);
int leftSubTreePostEnd = postStart + (rootInIndex - inStart);
root.left = buildTreeFunc(inorder, postorder, inStart, rootInIndex, postStart, leftSubTreePostEnd);
root.right = buildTreeFunc(inorder, postorder, rootInIndex + 1, inEnd, rightSubTreePostStart, postEnd - 1);
return root;
}
}