标签:length cti https src 输出 记录 img 示例 can
LeetCode 1372. Longest ZigZag Path in a Binary Tree二叉树中的最长交错路径【Medium】【Python】【DFS】
Given a binary tree root
, a ZigZag path for a binary tree is defined as follow:
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:
50000
nodes..[1, 100]
.给你一棵以 root
为根的二叉树,二叉树中的交错路径定义如下:
交错路径的长度定义为:访问过的节点数目 - 1(单个节点的路径长度为 0 )。
请你返回给定树中最长 交错路径 的长度。
示例 1:
输入:root = [1,null,1,1,1,null,null,1,1,null,1,null,null,null,1,null,1]
输出:3
解释:蓝色节点为树中最长交错路径(右 -> 左 -> 右)。
示例 2:
输入:root = [1,1,1,null,1,null,null,1,1,null,1]
输出:4
解释:蓝色节点为树中最长交错路径(左 -> 右 -> 左 -> 右)。
示例 3:
输入:root = [1]
输出:0
提示:
50000
个节点。[1, 100]
之间。DFS
递归时记录前面的节点是左节点还是右节点,以及深度。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def longestZigZag(self, root: TreeNode) -> int:
if root == None:
return 0
self.max_ = 0
self.dfs(root, 0, 0)
return self.max_
def dfs(self, root, prev, depth):
self.max_ = max(depth, self.max_)
if root.left:
# left->left
if prev == 0:
self.dfs(root.left, 0, 1)
# left->right
else:
self.dfs(root.left, 0, depth + 1)
if root.right:
# right->right
if prev == 1:
self.dfs(root.right, 1, 1)
# right->left
else:
self.dfs(root.right, 1, depth + 1)
LeetCode | 1372. Longest ZigZag Path in a Binary Tree二叉树中的最长交错路径【Python】
标签:length cti https src 输出 记录 img 示例 can
原文地址:https://www.cnblogs.com/wonz/p/12442704.html