• 1372. Longest ZigZag Path in a Binary Tree


    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:

    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

    题目:给定一棵二叉树,找其中最长的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. };

  • 相关阅读:
    腾讯云轻量4核8G12M带宽服务器租用价格和S5实例报价
    xpath 高级用法
    整数的运算
    如何缓解失业无收入焦虑状态?
    基于VUE + Echarts 实现可视化数据大屏快递业务数据
    啊哈C语言 第7章 有了它你能做更多的事(第27-28讲)
    Spring MVC 框架学习(七)---- 后端接口小练习(计算器与登陆拦截)
    Mysql---第六篇
    Webrtc支持FFMPEG硬解码之Intel(一)
    flink 查看写入starrocks的数据量 总行数
  • 原文地址:https://blog.csdn.net/qing2019/article/details/126647224