leetcode刷題筆記 222題 完全二叉樹的節點個數
阿新 • • 發佈:2020-10-08
leetcode刷題筆記 222題 完全二叉樹的節點個數
源地址:222. 完全二叉樹的節點個數
問題描述:
給出一個完全二叉樹,求出該樹的節點個數。
說明:
完全二叉樹的定義如下:在完全二叉樹中,除了最底層節點可能沒填滿外,其餘每層節點數都達到最大值,並且最下面一層的節點都集中在該層最左邊的若干位置。若最底層為第 h 層,則該層包含 1~ 2h 個節點。
示例:
輸入:
1
/
2 3
/ \ /
4 5 6輸出: 6
//使用遞迴,遍歷所有節點 /** * Definition for a binary tree node. * class TreeNode(_value: Int = 0, _left: TreeNode = null, _right: TreeNode = null) { * var value: Int = _value * var left: TreeNode = _left * var right: TreeNode = _right * } */ object Solution { def countNodes(root: TreeNode): Int = { var count = 0 def helper(root: TreeNode): Unit = { if (root != null) count += 1 if (root == null) return if (root.left != null) helper(root.left) if (root.right != null) helper(root.right) } helper(root) return count } } //使用二分思想,基於完全二叉樹性質 //對左右子樹進行計算, 若高度一致,則說明左子樹完全二叉樹,需要對右側統計 //反之,右子樹滿,需要對左子樹統計 /** * Definition for a binary tree node. * class TreeNode(_value: Int = 0, _left: TreeNode = null, _right: TreeNode = null) { * var value: Int = _value * var left: TreeNode = _left * var right: TreeNode = _right * } */ object Solution { def countNodes(root: TreeNode): Int = { def getHeight(root: TreeNode): Int = { var height = 0 var temp =root while (temp != null) { height += 1 temp = temp.left } return height } if (root == null) return 0 val lHeight = getHeight(root.left) val rHeight = getHeight(root.right) if (lHeight == rHeight) return math.pow(2, lHeight).toInt + countNodes(root.right) else return math.pow(2,rHeight).toInt + countNodes(root.left) } }