Appearance
1372 二叉树中的最长交错路径
code
javascript
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
var longestZigZag = function(root) {
let max = 0;
function traverse(root, direction, accumulate){
if(root === null){
return;
}
max = Math.max(max, accumulate);
if(direction === -1){
traverse(root.left, -1, 1);
traverse(root.right, 1, accumulate + 1);
}
if(direction === 1){
traverse(root.left, -1, accumulate + 1);
traverse(root.right, 1, 1);
}
}
traverse(root.left, -1, 1);
traverse(root.right, 1, 1);
return max;
};总结
- 说到底这类我感觉都没啥难的,携带着每一层的状态然后提公共的即可