1372. Longest ZigZag Path in a Binary Tree

£神魔★判官ぃ 2024-04-07 11:54 182阅读 0赞

You are given the root of a binary tree.

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, move to the right child of the current node; otherwise, move to the left child.
  • Change the direction from right to left or from left to right.
  • Repeat the second and third steps 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:

119390777e101e3b71c67a30d6f4727d.png

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

Example 2:

f603b2bf10a6fa9b717f33b042e092a9.png

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

Example 3:

  1. Input: root = [1]
  2. Output: 0

题目:给定一棵二叉树,找其中最长的zigzag路。

思路:递归,zigzag路不一定从根节点开始,因此需要记录以每个节点开始的最长zigzag路径,从底部往上回溯。因此从上往下时需要用direction(dir)记录每个节点是左节点还是右节点。如果是左节点(-1代表左节点),则从底部往上时需选择右子节点的zigzag路,如果是右节点(1代表右节点),则需选择其左子节点的zigzag路。根节点用0代表,则选择左子节点或右子节点最长的那条路。代码:

  1. /**
  2. * Definition for a binary tree node.
  3. * struct TreeNode {
  4. * int val;
  5. * TreeNode *left;
  6. * TreeNode *right;
  7. * TreeNode() : val(0), left(nullptr), right(nullptr) {}
  8. * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
  9. * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
  10. * };
  11. */
  12. class Solution {
  13. public:
  14. int helper(TreeNode* node, int& res, int dir){
  15. if(!node) return 0;
  16. int l = helper(node->left, res, -1);
  17. int r = helper(node->right, res, 1);
  18. res = max(res, max(l+1, r+1));
  19. if(dir == -1) return r+1;
  20. if(dir == 1) return l+1;
  21. return max(l,r)+1;
  22. }
  23. int longestZigZag(TreeNode* root) {
  24. int res = 0;
  25. helper(root, res, 0);
  26. return res-1;
  27. }
  28. };

发表评论

表情:
评论列表 (有 0 条评论,182人围观)

还没有评论,来说两句吧...

相关阅读