思路:
通法就是递归,其他方法暂不考虑
/** * 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 countNodes = function(root) { let result = 0 let nodes = data => { if (data) { nodes(data.left) nodes(data.right) result++ } } nodes(root) return result };
评论区