1. 程式人生 > 其它 >力扣222題(完全二叉樹的節點個數)

力扣222題(完全二叉樹的節點個數)

222.完全二叉樹的節點個數

基本思想:

遞迴

具體實現:

普通二叉樹求節點個數

1.遞迴引數以及返回值

引數:根節點

返回值:以該節點為根節點的二叉樹的節點數量

2.遞迴終止條件

遍歷到空節點的話,返回0,表明節點數為0

3.單層遞迴的邏輯

先求左子樹節點數量,再求右子樹節點數量,最後取總再加1(當前節點)

完全二叉樹求節點個數

兩種情況:

1.滿二叉樹,節點個數 = 2^樹深度-1

2.分別遞迴左孩子和右孩子,低軌道某一深度會有左孩子或右孩子是滿二叉樹,按照情況1來算

程式碼:

普通二叉樹求節點個數

class Solution {
    public int countNodes(TreeNode root) {
        
if (root == null) { return 0; } return countNodes(root.left) + countNodes(root.right) +1; } }

完全二叉樹求節點個數

class Solution {
    /**
     * 針對完全二叉樹的解法
     *
     * 滿二叉樹的結點數為:2^depth - 1
     */
    public int countNodes(TreeNode root) {
        TreeNode l = root, r = root;
        
int hl = 0, hr = 0; while (l != null){ l = l.left; hl++; } while (r != null){ r = r.right; hr++; } if(hl == hr){ return (int)Math.pow(2,hl) -1; } return 1 + countNodes(root.left) + countNodes(root.right); } }