222. 完全二叉树的节点个数🔖DFS

222. 完全二叉树的节点个数🔖DFS

https://leetcode-cn.com/problems/count-complete-tree-nodes/思路:通法就是递归,其他方法暂不考虑/** * Definition for a binary tree node. * function TreeNode(val, le...

2022年5月1日
96字
9 阅读

思路:

通法就是递归,其他方法暂不考虑

/**
 * 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
};

文章评论区

欢迎留言交流

未登录,请先注册或登录后发表评论。

Leave comment