LeetCode,leetcodeoj

來源:互聯網
上載者:User

LeetCode,leetcodeoj
題目描述:


Given a complete binary tree, count the number of nodes.


Definition of a complete binary tree from Wikipedia:
In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h.


統計一個完全樹的節點數。


完全樹的定義是,高度為h+1的樹,前h層的每層節點全滿。對於第h+1層,沒有葉子的節點均在右側。意味著,不存在左邊有些節點沒有葉子而右邊有些節點有葉子的情況。


實現思路:
遞迴求左右高度,如果高度相等,直接返回 Math.Pow(2, h) - 1;如果不等,遞迴求左子樹節點數+ 遞迴求右子樹的節點數 + 1;








實現代碼:



/** * Definition for a binary tree node. * public class TreeNode { *     public int val; *     public TreeNode left; *     public TreeNode right; *     public TreeNode(int x) { val = x; } * } */public class Solution {     public int CountNodes(TreeNode root)  {if(root == null){return 0;}var leftH = LeftDepth(root.left);var rightH = RightDepth(root.right);if(leftH == rightH){return (int)Math.Pow(2, leftH + 1) - 1;}else{return CountNodes(root.left) + CountNodes(root.right) + 1;} }    public int LeftDepth(TreeNode node){var h = 0;while(node != null){node = node.left;h++;}return h;    }public int RightDepth(TreeNode node){var h = 0;while(node != null){node = node.right;h++;}return h;}    }


著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.