Code idea
DFS
traverses each node, it means that it is impossible to go to dfs as the root node on the staggered path of the parent node, and the current node is not on the staggered path of the parent node and regards it as the root node dfs.
In the code we use 0,1 to refer to the next step forward.
Use a global variable to store the maximum value.
In addition, after I finished it, I went to see the solution of the eye problem and the ideas of the big guys. I saw that the idea of a double-hundred problem was similar to mine. I couldn't get out of the double-hundred. After 208ms, the time to pass the question can’t be changed any more (ノ ̄▽ ̄). What’s more interesting is that it takes more than ten ms to submit the same code, and it never runs out of 208ms again. It’s really metaphysical.
code
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int ans = 0;
void dfs(TreeNode* root, bool dir,int k){
//dir=0 ->left, dir=1 ->right
if(!root) return ;
ans = max(ans,k); //更新最大值
if(dir){
//当前结点是父节点的左节点
dfs(root->left,1,1); //下一步同向,作为根节点
dfs(root->right,0,k+1);//下一步反向,在父节点交错路径上
}
else{
dfs(root->left,1,k+1);
dfs(root->right,0,1);
}
return;
}
int longestZigZag(TreeNode* root) {
//最长交错路径,没算上root,因此ans不需要减1
dfs(root->left,1,1); //dfs左子树下一步向右走
dfs(root->right,0,1); //dfs右子树下一步向左走
return ans;
}
};