欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

LeetCode 112—路径总和

程序员文章站 2022-05-20 11:17:58
...

递归:

 public boolean hasPathSum(TreeNode root, int sum) {
		 if(root==null) return false;
		 if(root.left==null&&root.right==null&&sum==0) return true;
		 return hasPathSum(root.left, sum-root.val)||hasPathSum(root.right, sum-root.val);
	        
	    }

迭代:

public boolean hasPathSum(TreeNode root, int sum) {
		 if (root==null) return false;
	     Stack<TreeNode> stack=new Stack<TreeNode>();
	     stack.push(root);
	     while (!stack.empty()) {
	            TreeNode t = stack.pop();
	            if (t.left==null && t.right==null) {
	                if (t.val == sum) return true;
	            }
	            if (t.right!=null) {
	                t.right.val += t.val;
	                stack.push(t.right);
	            }
	            if (t.left!=null) {
	                t.left.val += t.val;
	                stack.push(t.left);
	            }
	        }
	        return false;

		 
		 
	 }