LeetCode 1372. Longest ZigZag Path in a Binary Tree二叉樹中的最長交錯路徑【Medium】【Python】【DFS】
Problem
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]
.
問題
給你一棵以 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
遞歸時記錄前面的節點是左節點還是右節點,以及深度。
Python3代碼
# 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)