Problem 1 Longest ZigZag Path in a Binary Tree

Method 1 Backtracking

// Some code

```java

 /*
Assumption & Clarification
    - input: regular binary tree
    - output: longest path from any node to any node, the maximum path length
High Level
    - backtracking from top to buttom to search all path from node to node
Middle Level
    - base case,
        -  null return
    - return result
        - each time
    - each Level
        - valid node from current Level
    - branches
        - left, right (if they exists)
Recursion TreeNode.  
                                     cur
                    /               \               \                        \
               (!isleft,cur.left) (isleft, cur.left)   (!isleft, cur.right)   (!isleft, cur.right)   
                /.    \.     /.    \.  
      
TC & SC O(n), O(1)
 */
class Solution {
    public int longestZigZag(TreeNode root) {
        int[] globalMax = new int[]{0};
        if (root == null) {
            return globalMax[0];
        }
        int curPossLength = 0;
        backTracking(root, curPossLength, true, globalMax);
        backTracking(root, curPossLength, false, globalMax);
        return globalMax[0];
    }
    private void backTracking(TreeNode cur, int curPossLength, boolean isPrevLeft, int[] globalMax) {
        // base case 
        if (cur == null) {
            return;
        }
        // return result
        globalMax[0] = Math.max(globalMax[0], curPossLength);
        curPossLength++;

        // current , induction rule?
        // subproblem
        if (isPrevLeft) { // previous is left
            backTracking(cur.left, 1, true, globalMax); // ่ฟ™้‡Œๆ˜ฏ1
            backTracking(cur.right, curPossLength, false, globalMax);
        } 
        else { // previous is right
            backTracking(cur.left, curPossLength, true, globalMax);
            backTracking(cur.right, 1, false, globalMax);
        }
        curPossLength--;
    }
}
```java

Method 2 Pure Recursion

Last updated