zoukankan      html  css  js  c++  java
  • 树的遍历 | 路径总和

    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.
    

    思路1: 遍历

    在遍历的过程中,保留从根节点到当前节点的值,在访问到某个节点时,如果该节点为叶子节点,且sum = 0,则返回True

    class Solution(object):
        def hasPathSum(self, root, sum):
            """
            :type root: TreeNode
            :type sum: int
            :rtype: bool
            dfs
            """
            if root is None:
                return False
            root.sum = sum - root.val
            stack = [root]
            while len(stack):
                while root:
                    left = root.left
                    if left:
                        left.sum = root.sum - left.val
                        stack.append(left)
                    root = left
                    
                root = stack.pop()
                if root:
                    if root.sum == 0 and root.left is None and root.right is None:
                        return True
                    if root.right:
                        right = root.right
                        right.sum = root.sum - right.val
                        stack.append(right)
                        root = right
            return False
    

    思路2: 递归,

    递归判断左子树或右子树是否存在 sum - root.val 的路径。

    class Solution(object):
        def hasPathSum(self, root, sum):
            """
            :type root: TreeNode
            :type sum: int
            :rtype: bool
            dfs
            """
            if root is None:
                return False
            sum = sum  - root.val
            if sum == 0 and root.left == None and root.right == None:
                return True
            else:
                return self.hasPathSum(root.left, sum) or self.hasPathSum(root.right, sum)
    
  • 相关阅读:
    Oracle中的to_date参数含义
    Oracle 中 IW和WW 有何差别
    iBaits.Net(1):简介与安装
    带你逛逛诺基亚芬兰总部:满满都是回忆啊
    LINQ的分组聚合技术
    WPF的Docking框架 ——AvalonDock
    iBatis.Net(3):创建SqlMapper实例
    iBatis.Net(2):基本概念与配置
    C#异步编程及其同步机制
    web使用
  • 原文地址:https://www.cnblogs.com/xmxj0707/p/10381227.html
Copyright © 2011-2022 走看看