二叉树路径和系列-leetcode 112. Path Sum

题目描述:

Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.

Note: A leaf is a node with no children.

Example:

Given the below binary tree and sum = 22,

      5
     / \
    4   8
   /   / \
  11  13  4
 /  \      \
7    2      1

return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.

https://blog.csdn.net/orangefly0214/article/details/94589630

思路1:递归

二叉树路径和系列都是一个思路,需要用到递归的思想;

递归结束的条件:二叉树到达叶子节点,如果叶子节点处,路径和和给定的相等,则返回true,否则返回false。我们在递归的过程中,可以对给定的target做减法,这样如果递归到叶子节点,刚好减到0,则满足条件,否则不满足。

实现:

//递归的方法:和求二叉树路径和是一样的
//递归结束的条件:刚好到达二叉树的叶子节点或者当前节点为空
public boolean hasPathSum(TreeNode root, int target) {
	if(root==null){
		return false;
	}
	//到达叶子节点,路径和刚好为target,则找到
	if(root.left==null&&root.right==null&&target-root.val==0){
		return true;
	}
	return hasPathSum(root.left,target-root.val)||hasPathSum(root.right,target-root.val);
}

思路2:迭代,用到双栈

用栈模拟递归的过程,通常需要先压入右节点,再压入左节点。我们可以使用两个栈,每次在压入节点的同时,也在另一个栈中压入从根节点到当前节点的和。每次弹出节点后,同时弹出节点及对应的路径和,判断当前节点是否是叶子节点,若是,则判断它对应的路径和是否与我们给定的sum值相等,若相等。

若栈中所有的节点全部弹出,还是没有返回,则表明没有满足条件的路径,此时返回false;

//迭代的方法:双栈
public boolean hasPathSum2(TreeNode root, int target) {
	if(root==null){
		return false;
	}
	Stack<TreeNode> s=new Stack<>();
	Stack<Integer> sumStack=new Stack<>();
	s.push(root);
	sumStack.push(root.val);
	while(!s.isEmpty()&&root!=null){
		TreeNode curr=s.pop();
		int currSum=sumStack.pop();
		if(curr.left==null&&curr.right==null){
			if(currSum==target){
				return true;
			}
		}
		if(curr.right!=null){
			s.push(curr.right);
			sumStack.push(currSum+curr.right.val);
		}
		if(curr.left!=null){
			s.push(curr.left);
			sumStack.push(currSum+curr.left.val);
		}
	}
	return false;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值