回到技术博客

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

思路:

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

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

— 写于生活,留给未来 —

最后更新于 2024-11-17

树下留言

LET’S TALK

文字是一次相遇。很高兴听到你的声音。

评论加载中…