本文主要是介绍Leetcode 222:完全二叉树的节点个数,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
给你一棵 完全二叉树 的根节点 root
,求出该树的节点个数。
递归遍历1
public static int countNodes(TreeNode root){return preorder(root);}//计算树的节点个数public static int preorder(TreeNode root){int count=0;if(root==null) return 0;int left=preorder(root.left);int right=preorder(root.right);count=left+right+1; //树的节点个数=左子树节点个数+右子树节点个数+1(根节点)return count;}
递归遍历2(精简版)
public int countNodes(TreeNode root) {if(root == null) {return 0;}return countNodes(root.left) + countNodes(root.right) + 1;}
这篇关于Leetcode 222:完全二叉树的节点个数的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!