[leetcode]Count Complete Tree Nodes
2015-11-20 10:49
627 查看
题目描述如下:
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.
因为树这样的题目也没办法很好的调试,所以之前也是CE了好多遍
第一版的代码如下:
然后就TLE了。想想也是,毕竟是medium难度的题目,如果就这样暴力破解未免太过分了。
再读了一遍题目,完全二叉树左子树高度和右子树高度一致,这时候若树的高度为height,那么一共有height^2-1个节点,这个地方可以进行剪枝。所以,只要递归左右两边子树高度不同的部分就好。利用这个思路再写就AC了。附上代码:
题目链接:https://leetcode.com/problems/count-complete-tree-nodes/
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.
因为树这样的题目也没办法很好的调试,所以之前也是CE了好多遍
第一版的代码如下:
public class Solution { public int res; Solution(){ this.res = 0; } public void addCount(){ this.res++; } public int getCount(){ return this.res; } public int countNodes(TreeNode root) { if(root == null) return 0; addCount(); if(root.left == null && root.right == null) return getCount(); if(root.left != null){ countNodes(root.left); } if(root.right != null) countNodes(root.right); return getCount(); } }
然后就TLE了。想想也是,毕竟是medium难度的题目,如果就这样暴力破解未免太过分了。
再读了一遍题目,完全二叉树左子树高度和右子树高度一致,这时候若树的高度为height,那么一共有height^2-1个节点,这个地方可以进行剪枝。所以,只要递归左右两边子树高度不同的部分就好。利用这个思路再写就AC了。附上代码:
public class Solution { public int res; Solution(){ this.res = 0; } public int getLeftHeight(TreeNode root){ int height = 0; while(root.left != null) { root = root.left; height ++; } return height; } public int getRightHeight(TreeNode root){ int height = 0; while(root.right != null) { root = root.right; height ++; } return height; } public int countNodes(TreeNode root) { if(root == null) return 0; int lheight = getLeftHeight(root); int rheight = getRightHeight(root); if(lheight == rheight) return (2 << lheight) - 1; else return countNodes(root.left) + countNodes(root.right) + 1; } }
题目链接:https://leetcode.com/problems/count-complete-tree-nodes/
相关文章推荐
- 【Leetcode】Reverse Nodes in k-Group
- 用nodej和glub-watcher写的监听go 项目自动编译,很鸡肋
- Nodejs+Mongo+WebAPI
- 使用Node.js的socket.io模块开发实时web程序
- 使用Node.js的socket.io模块开发实时web程序
- Nodejs Express 开发必备知识点
- nodejs事件轮询详述
- 【Leetcode】Remove Nth Node From End of List
- Hadoop NameNode元数据相关文件目录解析
- node.js中的控制台
- delete node_modules dir in windows
- Node.js框架之express
- 基于html5和nodejs相结合实现websocket即使通讯
- Node初学者入门,一本全面的NodeJS教程(推荐阅读)
- 浅析nodejs实现Websocket的数据接收与发送
- Node.js中使用socket创建私聊和公聊聊天室
- nodejs
- 详解nodejs中使用socket的私聊和公聊的办法
- nodejs express template (模版)的使用 (ejs + express)
- node的“宏任务(macro-task)”和“微任务(micro-task)”机制