[leetcode] 1372. Longest ZigZag Path in a Binary Tree

Description

Given a binary tree root, a ZigZag path for a binary tree is defined as follow:

  • Choose any node in the binary tree and a direction (right or left).
  • If the current direction is right then move to the right child of the current node otherwise move to the left child.
  • Change the direction from right to left or right to left.
  • Repeat the second and third step until you can’t move in the tree.

Zigzag length is defined as the number of nodes visited - 1. (A single node has a length of 0).

Return the longest ZigZag path contained in that tree.

Example 1:

Input: root = [1,null,1,1,1,null,null,1,1,null,1,null,null,null,1,null,1]
Output: 3
Explanation: Longest ZigZag path in blue nodes (right -> left -> right).

Example 2:

Input: root = [1,1,1,null,1,null,null,1,1,null,1]
Output: 4
Explanation: Longest ZigZag path in blue nodes (left -> right -> left -> right).

Example 3:

Input: root = [1]
Output: 0

Constraints:

  • Each tree has at most 50000 nodes…
  • Each node’s value is between [1, 100].

分析

题目的意思是:找出二叉树的最长zigzag链,这道题我看了一下提示,要用动态规划的思想,用isLeft标记当前的结点需要向左遍历还是向右遍历,为True的话,下一步可以保持向左,也可以向右,向左的话,step+1,向右的话step要置1,表示不能跟构成zigzag链了,需要从头开始计数;相反为False的话,下一步可以保持向右,也可以向左,向右的话,step+1,向左的话,step要置1,表示不能构成zigzag链了,需要从头开始计数。

代码

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def maxZigZag(self,root,isLeft,step):
        if(root is None):
            return
        self.maxStep=max(self.maxStep,step)
        if(isLeft):
            self.maxZigZag(root.right,True,1)
            self.maxZigZag(root.left,False,step+1)
        else:
            self.maxZigZag(root.right,True,step+1)
            self.maxZigZag(root.left,False,1)
        
    def longestZigZag(self, root: TreeNode) -> int:
        self.maxStep=0
        self.maxZigZag(root,True,0)
        self.maxZigZag(root,False,0)
        return self.maxStep

参考文献

[LeetCode] [Java/C++] DFS Solution with comment - O(N) - Clean code

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值