leetcode 222 Count Complete Tree Nodes (計算完全二叉樹節點數),leetcodenodes

來源:互聯網
上載者:User

leetcode 222 Count Complete Tree Nodes (計算完全二叉樹節點數),leetcodenodes
1. 問題描述

  計算完全二叉樹的節點數。對於完全二叉樹的定義可參考wikipedia上面的內容。

2. 方法與思路

  最簡單也最容易想到的方法就是使用遞迴,分別遞迴計算左右子樹的節點數的和。但此方法最容易逾時,一般不可取。
  

int countNodes(TreeNode* root) {        if(root == NULL) return 0;        else if(root->left == NULL) return 1;        return countNodes(root->left) + countNodes(root->right);    }

  用這段代碼提交,果真還是逾時了。那麼如何改進呢?
  那就是利用滿二叉樹來簡化演算法。滿二叉樹的節點數計算公式為N = 2^h - 1. h為二叉樹的層數。遞迴過程如下:
  

/** * Definition for a binary tree node. * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    int nodesofMan(TreeNode* root){ //判斷是否為滿二叉樹,若是返回該滿二叉樹的節點數。        int l=1,r=1;        TreeNode *node = root;        while(node->left)        {            l++;            node = node->left;        }        node = root;        while(node->right)        {            r++;            node = node->right;        }        if(l == r)            return (int)pow(2,(double)l) - 1;        else            return 0;    }    int countNodes(TreeNode* root) {        if(root == NULL) return 0;        //else if(root->left == NULL) return 1;        if(nodesofMan(root)) return nodesofMan(root);        else            return countNodes(root->left) + countNodes(root->right) +1;    }};

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.