zoukankan      html  css  js  c++  java
  • LeetCode 112: Path Sum

    /**
     * 112. Path Sum
     * 1. Time:O(n)  Space:O(h)
     * 2. Time:O(n)  Space:O(h)
     */
    
    // 1. Time:O(n)  Space:O(h)
    class Solution {
        public boolean hasPathSum(TreeNode root, int sum) {
            if(root==null) return false;
            if(root.left==null && root.right==null)
                return sum==root.val;
            return hasPathSum(root.left,sum-root.val) || hasPathSum(root.right,sum-root.val);
        }
    }
    
    // 2. Time:O(n)  Space:O(h)
    class Solution {
        public boolean hasPathSum(TreeNode root, int sum) {
            if(root==null) return false;
            Stack<TreeNode> nodeStack = new Stack<>();
            Stack<Integer> sumStack = new Stack<>();
            nodeStack.push(root);
            sumStack.push(sum-root.val);
            while(!nodeStack.isEmpty()){
                TreeNode node = nodeStack.pop();
                int curSum = sumStack.pop();
                if(node.left==null && node.right==null&&curSum==0)
                    return true;
                if(node.left!=null){
                    nodeStack.push(node.left);
                    sumStack.push(curSum-node.left.val);
                }
                if(node.right!=null){
                    nodeStack.push(node.right);
                    sumStack.push(curSum-node.right.val);
                }
            }
            return false;
        }
    }
    
  • 相关阅读:
    luogu P3295 [SCOI2016]萌萌哒
    luogu P4916 魔力环
    CF997C Sky Full of Stars
    CF961G Partitions
    android屏蔽软键盘并且显示光标
    设置和获取Android中各种音量
    自定义广播
    发送广播
    android取高度
    Java数字格式化
  • 原文地址:https://www.cnblogs.com/AAAmsl/p/12849347.html
Copyright © 2011-2022 走看看