diff options
author | jack <[email protected]> | 2024-06-14 13:13:15 -0600 |
---|---|---|
committer | jack <[email protected]> | 2024-06-14 13:13:15 -0600 |
commit | d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa (patch) | |
tree | 96df922dae2a5073d9a50ea70c7aae6aa37e3ebe /longest_zigzag_bt.c | |
download | leetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.tar.gz leetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.zip |
initial
Diffstat (limited to 'longest_zigzag_bt.c')
-rw-r--r-- | longest_zigzag_bt.c | 47 |
1 files changed, 47 insertions, 0 deletions
diff --git a/longest_zigzag_bt.c b/longest_zigzag_bt.c new file mode 100644 index 0000000..e5f1e9d --- /dev/null +++ b/longest_zigzag_bt.c @@ -0,0 +1,47 @@ +// 1372. Longest ZigZag Path in a Binary Tree +#include <math.h> +#include <stdlib.h> + +/* + * given the 'root' of a binary tree. a zigzag path for a binary tree is defined + * as follows + * - choose any node in the binary tree and a direction (left or right) + * - if the current direction is right, move to the right child of the current + * node + * - change the direction from right to left or from left to right + * - repeat the second nd third steps until you cannot move in the tree + * zigzag length is defined as the number of nodes visited - 1. return longest + * zigzag + */ + +struct TreeNode { + int val; + struct TreeNode *left; + struct TreeNode *right; +}; + +typedef struct { + int left; + int right; +} data; + +data process(struct TreeNode *root, int *max) { + data res; + if (!root) { + res.left = -1; + res.right = -1; + return res; + } + data l_tree = process(root->left, max); + data r_tree = process(root->right, max); + res.left = 1 + r_tree.right; + res.right = 1 + l_tree.left; + *max = fmax(fmax(res.left, *max), res.right); + return res; +} + +int longestZigZag(struct TreeNode *root) { + int max = 0; + process(root, &max); + return max; +} |