[Binary tree] The number of nodes in a complete binary tree

0x00 topic

Give you 完全二叉树the root node of a root
tree Find the root of the tree节点个数


0x01 Ideas

Calculate the 某个node 节点个数: Calculate
the calculation of the subtree and add the number of nodes to the calculation of the subtree节点个数
节点个数
当前1

The calculation of the left and right subtrees
becomes -> the calculation of the 某个node , 节点个数
which becomes the recursion . The
end condition is:节点为空


0x02 solution

language:Swift

tree node:TreeNode

public class TreeNode {
    public var val: Int
    public var left: TreeNode?
    public var right: TreeNode?
    public init() { self.val = 0; self.left = nil; self.right = nil; }
    public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; }
    public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) {
        self.val = val
        self.left = left
        self.right = right
    }
}

solution:

func countNodes(_ root: TreeNode?) -> Int {
    // 结束条件
    guard let r = root else { return 0 }

    // 左 子树的 节点个数
    let left = countNodes(r.left)
    // 右 子树的 节点个数    
    let right = countNodes(r.right)
	// 当前节点树的 节点个数
    return left + right + 1
}

small editor app

Please add image description


Guess you like

Origin blog.csdn.net/xjh093/article/details/123104523