【代码随想录算法训练营Day18】● 513.找树左下角的值 ● 112. 路径总和 113.路径总和ii ● 106.从中序与后序遍历序列构造二叉树 105.从前序与中序遍

Day 18 第六章 二叉树 part05

  • 今日内容
    • ● 513.找树左下角的值
    • ● 112. 路径总和 113.路径总和ii
    • ● 106.从中序与后序遍历序列构造二叉树 105.从前序与中序遍历序列构造二叉树

513.找树左下角的值

自己的思路 - 层序遍历(✅通过但时间太长)

用层序遍历,把每层第一个数加入一个新栈,返回栈顶即可

public static int findBottomLeftValue(TreeNode root) {
	Queue<TreeNode> queue = new LinkedList<>();
	LinkedList<TreeNode> stack = new LinkedList<>();
	if(root != null) queue.offer(root);
	while(!queue.isEmpty()){
		//队列里元素的个数就是每一层元素的个数
		int size =  queue.size();
		//System.out.println("peek:"+queue.peek().toString());
		stack.push(queue.peek());
		//不能直接把queue.size()写进for循环,因为循环的时候queue.size()会变
		for(int i = 0; i < size; i++){
			TreeNode poll = queue.poll();
			System.out.println(poll.val+" ");
			if(poll.left != null) queue.offer(poll.left);
			if(poll.right != null) queue.offer(poll.right);
		}
	}
	return stack.peek().val;
}

随想录代码 - 层序遍历

优化思路:只定义一个int类型的res,for循环的第一个数就赋给res即可

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 poll = queue.poll();
			if (i == 0) {
				res = poll.val;
			}
			if (poll.left != null) {
				queue.offer(poll.left);
			}
			if (poll.right != null) {
				queue.offer(poll.right);
			}
		}
	}
	return res;
}

随想录代码 - 递归

思路:找深度最大的叶子节点最左侧的节点

private int maxDeep = -1;//二叉树的最大深度
private int res = 0;//结果
public int findBottomLeftValue(TreeNode root) {
	res = root.val;
	findLeftValue(root,0);
	return res;
}
private void findLeftValue (TreeNode root,int deep) {
	//节点为空
	if (root == null) return;
	//当递归到子节点,结束递归
	if (root.left == null && root.right == null) {
		//如果比之前记录的深度要深
		if (deep > maxDeep) {
			//更新结果
			res = root.val;
			//更新最大深度
			maxDeep = deep;
		}
	}
	if (root.left != null) findLeftValue(root.left,deep + 1);
	if (root.right != null) findLeftValue(root.right,deep + 1);
}
if (root.left != null) findLeftValue(root.left,deep + 1);
//相当于
if (root.left != null) {
	deep ++;
	findLeftValue(root.left,deep);
	deep --;	//回溯的过程
}

112.路径总和+113.路径总和ii

112.路径总和

思路

同113,只是返回值变为true和false

代码
public static boolean hasPathSum(TreeNode root, int targetSum) {
	if (root == null) {
		return false;
	}
	targetSum -= root.val;
	// 叶子结点
	if (root.left == null && root.right == null) {
		return targetSum == 0;
	}
	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;
}

113.路径总和ii

思路

走到哪个节点就用targetSum-root.val,并且把root加入path
走到叶子节点通过判断targetSum是否为0来确定是否是一条正确的路径
然后进行递归
递归之后进行回溯!重新进行path

代码&重点
  1. 必须要回溯path
  2. 当把path赋值给res时,得先用path新建一个数组new ArrayList<>(path),再将新的数组赋值给res,因为path回溯到最后一定为空
public static List<List<Integer>> pathSum(TreeNode root, int targetSum) {
	List<List<Integer>> res = new ArrayList<>();
	if(root == null) return res;
	dfs(root, targetSum, new ArrayList<>(), res);
	return res;
}
public static void dfs(TreeNode root, int targetSum, List<Integer> path, List<List<Integer>> res){
	path.add(root.val);
	targetSum -= root.val;
	//到叶子节点找到路径,添加到结果
	if (root.left == null && root.right == null && targetSum == 0) {
		//❗❗❗新创建一个数组给res赋值
		res.add(new ArrayList<>(path));
	}
	//到叶子节点没有路径
	if(root.left == null && root.right == null && targetSum != 0){
		return;
	}
	if(root.left != null){
		//System.out.println("L root:"+root.val+" root.left:"+root.left.val);
		dfs(root.left, targetSum, path, res);
		//System.out.print("L 回溯 root:"+root.val+" root.left:"+root.left.val+" "+path);
		//❗❗❗必须要回溯
		path.remove(path.size() - 1);
		//System.out.print("----->"+path);
		//System.out.println();
	}
	if(root.right != null){
		//System.out.println("R root:"+root.val+" root.right:"+root.right.val);
		dfs(root.right, targetSum, path, res);
		//System.out.print("R 回溯 root:"+root.val+" root.right:"+root.right.val+" "+path);
		//❗❗❗必须要回溯
		path.remove(path.size() - 1);
		//System.out.print("----->"+path);
		//System.out.println();
	}
}

pFG786f.png

106.从中序与后序遍历序列构造二叉树+105

105.递归代码

  • 参考视频:https://b23.tv/NPXvK67
  • 优化思路
    1. 通过哈希表直接在中序遍历中找根节点,不通过for循环
    2. 把下标加到参数里,不需要新建数组再拷贝
/*
int[] preorder = {1,2,4,3,6,7};
int[] inorder = {4,2,1,6,3,7};

	前序:中左右;中序:左中右
	根   1
		 pre         in
	左   2,4         4,2
	右   3,6,7       6,3,7

	根   2
	左   4
	右   null

	根   3
	左   6
	右   7
	递归的问题
 */
 public static TreeNode buildTree(int[] preorder, int[] inorder) {
	if(preorder.length == 0 || inorder.length == 0) return null;
	//创建根节点
	int rootValue = preorder[0];
	TreeNode root = new TreeNode(rootValue);
	//区分左右子树
	for(int i = 0; i < inorder.length; i ++){
		if(inorder[i] == rootValue){
			//0 ~ i-1 是左子树
			//i+1 ~ inorder.length-1 是右子树
			//Arrays.copyOfRange()是左闭右开区间
			int[] inLeft = Arrays.copyOfRange(inorder, 0, i);//[4, 2]
			int[] inRight = Arrays.copyOfRange(inorder, i + 1, inorder.length);//[6, 3, 7]

			//拆分前序遍历的数组
			int[] preLeft = Arrays.copyOfRange(preorder, 1, i + 1);//[2, 4]
			int[] preRight = Arrays.copyOfRange(preorder, i + 1, inorder.length);//[3, 6, 7]

			root.left = buildTree(preLeft, inLeft);
			root.right = buildTree(preRight, inRight);
			break;
		}
	}
	return root;
}

105.随想录代码

Map<Integer, Integer> map;
public TreeNode buildTree(int[] preorder, int[] inorder) {
	map = new HashMap<>();
	for (int i = 0; i < inorder.length; i++) { // 用map保存中序序列的数值对应位置
		map.put(inorder[i], i);
	}

	return findNode(preorder, 0, preorder.length, inorder,  0, inorder.length);  // 前闭后开
}

public TreeNode findNode(int[] preorder, int preBegin, int preEnd, int[] inorder, int inBegin, int inEnd) {
	// 参数里的范围都是前闭后开
	if (preBegin >= preEnd || inBegin >= inEnd) {  // 不满足左闭右开,说明没有元素,返回空树
		return null;
	}
	int rootIndex = map.get(preorder[preBegin]);  // 找到前序遍历的第一个元素在中序遍历中的位置
	TreeNode root = new TreeNode(inorder[rootIndex]);  // 构造结点
	int lenOfLeft = rootIndex - inBegin;  // 保存中序左子树个数,用来确定前序数列的个数
	root.left = findNode(preorder, preBegin + 1, preBegin + lenOfLeft + 1,
						inorder, inBegin, rootIndex);
	root.right = findNode(preorder, preBegin + lenOfLeft + 1, preEnd,
						inorder, rootIndex + 1, inEnd);

	return root;
}

106.代码

与105类似

  • 22
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值