黄哥Python: 222题 Count Complete Tree Nodes, 解题思路

209 阅读1分钟
原文链接: zhuanlan.zhihu.com

1、先读题,求一个完全二叉树的node 总数。

看一下完全二叉树定义

2、用最笨的方法解决这个问题,当然有比较简单的方法。

bfs 遍历求所有nodes 的数组,再返回这个数组的长度。

3、黄哥用Python, Go, Java 三种编程语言实现它。

Python 代码

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
# 黄哥Python培训 黄哥所写
class Solution:
    def countNodes(self, root: TreeNode) -> int:
        if root is None:
            return 0
        res =[]
        def dfs(root):
            if root is None:
                return
            res.append(root.val)
            dfs(root.left)
            dfs(root.right)
        dfs(root)
        return len(res)

Go 代码

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
// 黄哥Python培训 黄哥所写
func countNodes(root *TreeNode) int {
    if root == nil {
        return 0
    }
    var res []int
    dfs(root, &res)
    return len(res)
}

func dfs(root *TreeNode, res *[]int) {
    if root == nil {
        return
    }
    *res = append(*res, root.Val)
    dfs(root.Left, res)
    dfs(root.Right, res)
}

Java 代码

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */

// 黄哥Python培训 黄哥所写
class Solution {
    public static List<Integer> res = new ArrayList<Integer>();
    public int countNodes(TreeNode root) {
        if (root == null) return 0;
        res.clear();
        dfs(root);
        return res.size();
        
    }
    public static void dfs(TreeNode root) {
        if (root == null) {
            return;
        }
        res.add(root.val);
        dfs(root.left);
        dfs(root.right);
        
    }
}
黄哥:黄哥Python:提醒要转行当程序员的朋友,学习要分先后主次zhuanlan.zhihu.com图标黄哥:黄哥Python培训是这样训练学员的zhuanlan.zhihu.com图标