LeetCode 222. 完全二叉樹的節點個數 (遍歷+打編號)

完全二叉樹的節點個數

/**
 * 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 ans = 0;
    int countNodes(TreeNode* root) {
        dfs(root,1);
        return ans;
    }
    void dfs(TreeNode* root,int idx){
        if(!root){
            return;
        }
        ans = max(ans,idx);
        dfs(root->left,idx<<1);
        dfs(root->right,(idx<<1)|1);
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章