• 【LeetCode】112.路径总和(递归和迭代实现,Java)


    题目地址:https://leetcode-cn.com/problems/path-sum/

    题目

    1. 路径总和
      给定一个二叉树和一个目标和,判断该树中是否存在根节点到叶子节点的路径,这条路径上所有节点值相加等于目标和。

    说明: 叶子节点是指没有子节点的节点。

    示例:
    给定如下二叉树,以及目标和 sum = 22,

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

    返回 true, 因为存在目标和为 22 的根节点到叶子节点的路径 5->4->11->2。

    递归实现

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

    迭代实现

    	public boolean hasPathSum(TreeNode root, int sum) {
    	if(root == null ) return false;
    	Stack<TreeNode> node = new Stack<>();
    	Stack<Integer>  path = new Stack<>();
    	node.push(root);
    	path.push(root.val);
    	while(!node.isEmpty()){
    		TreeNode t = node.pop();
    		int val = path.pop();
    		if(t.left == null && t.right == null && val == sum) 
    			return true;
    		if(t.left!=null){
    			node.push(t.left);
    			path.push(t.left.val+val);
    			}
    		if(t.right!=null){
    			node.push(t.right);
    			path.push(t.right.val+val);
    			}		
    }
    	return false;
    }
    
  • 相关阅读:
    3D数学 矩阵的更多知识(5)
    D3D中的光照(1)
    双节棍(C语言版)
    D3D中的Alpha融合技术(1)
    D3D编程必备的数学知识(5)
    Direct3D中的绘制(1)
    初始化Direct3D(2)
    D3D中的纹理映射(2)
    Direct3D中的绘制(1)
    D3D编程必备的数学知识(2)
  • 原文地址:https://www.cnblogs.com/hzcya1995/p/13308079.html
Copyright © 2020-2023  润新知