Advertisement
jayati

Longest ZigZag Path in a Binary Tree

May 11th, 2024
770
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.03 KB | None | 0 0
  1. //first approach
  2. class Solution {
  3. public:
  4.     int pathLength = 0;
  5.     void dfs(TreeNode* node, int left, int right) {
  6.         if (node == nullptr) {
  7.             return;
  8.         }
  9.         pathLength = max({pathLength, left,right});
  10.         dfs(node->right,0,left+1);
  11.         dfs(node->left, right+1, 0);
  12.  
  13.     }
  14.  
  15.     int longestZigZag(TreeNode* root) {
  16.         dfs(root, 0, 0);
  17.        
  18.         return pathLength;
  19.     }
  20. };
  21. // second approach
  22. class Solution {
  23. public:
  24.     int pathLength = 0;
  25.     void dfs(TreeNode* node, bool goLeft, int steps) {
  26.         if (node == nullptr) {
  27.             return;
  28.         }
  29.         pathLength = max(pathLength, steps);
  30.         if (goLeft) {
  31.             dfs(node->left, false, steps + 1);
  32.             dfs(node->right, true, 1);
  33.         } else {
  34.             dfs(node->left, false, 1);
  35.             dfs(node->right, true, steps + 1);
  36.         }
  37.     }
  38.  
  39.     int longestZigZag(TreeNode* root) {
  40.         dfs(root, false, 0);
  41.         dfs(root, true, 0);
  42.         return pathLength;
  43.     }
  44. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement