程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> LeetCode -- Count Complete Tree Node

LeetCode -- Count Complete Tree Node

編輯:C++入門知識

LeetCode -- Count Complete Tree Node


題目描述:


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;
	}
    
}

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved