LeetCode-树-Easy

记录了初步解题思路 以及本地实现代码;并不一定为最优 也希望大家能一起探讨 一起进步




226. Invert Binary Tree 翻转二叉树

利用队列 按行遍历 每经过一个根节点 将其左右子树对调

class TreeNode(object):
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

def invertTree(root):
    """
    :type root: TreeNode
    :rtype: TreeNode
    """
    l=[root]
    while l:
        node = l.pop()
        if not node:
            continue
        tmp = node.left
        node.left=node.right
        node.right=tmp
        l.append(node.left)
        l.append(node.right)
        
    return root

235. Lowest Common Ancestor of a Binary Search Tree 二叉搜索树的最近公共祖先

根据二叉搜索树特性 根节点不可能比两个节点都大 或都小
注意:p,q为节点 不是数值

class TreeNode(object):
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None
        
def lowestCommonAncestor(root, p, q):
    """
    :type root: TreeNode
    :type p: TreeNode
    :type q: TreeNode
    :rtype: TreeNode
    """
    while root:
        v = root.val
        if v<p.val and v<q.val:
            root = root.right
        elif v>p.val and v>q.val:
            root = root.left
        else:
            return root

404. Sum of Left Leaves 左叶子之和

扫描每个节点 对其左子节点判断 是否为叶节点 满足则累加

class TreeNode(object):
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

def sumOfLeftLeaves(root):
    """
    :type root: TreeNode
    :rtype: int
    """
    def isLeaf(node):
        return (not node.left) and (not node.right)
    l=[root]
    ret = 0
    while l:
        node = l.pop()
        if not node:
            continue
        l.append(node.left)
        l.append(node.right)
        if node.left and isLeaf(node.left):
            ret+=node.left.val
    return ret

437. Path Sum III 路径总和 III

双层递归
一层用来遍历所有节点
一层用来遍历从这个节点出发的情况
注意 当sum==val时不能停止 需要继续往下找 存在和为0的情况

class TreeNode(object):
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None


def pathSum(root, sum):
    """
    :type root: TreeNode
    :type sum: int
    :rtype: int
    """
    def start(root,sum):
        ret = 0
        if not root:
            return ret
        if root.val == sum:
            ret+=1
        
        if root.left:
            ret += start(root.left,sum-root.val)
        if root.right:
            ret += start(root.right,sum-root.val)
            
        return ret
    
    if not root:
        return 0
    res = start(root,sum)
    res += pathSum(root.left,sum)
    res += pathSum(root.right,sum)
    
    return res
    

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值