摘要: 题目:Given a binary tree, determine if it is height-balanced.For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees ofeverynode never differ by more than 1.思路比较简单: 先看左右子树:平衡->看左右子树的高度差,不超过1则当前树平衡,否则失衡;不平衡->当前树不平衡;代码如下, 1 bool isBalanced 阅读全文
posted @ 2013-11-16 18:33 月窟仙人 阅读(129) 评论(0) 推荐(0) 编辑
摘要: 题目描述:Given a binary tree, find its minimum depth.The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.一看到这个题目的时候,想一层一层的数一下,仔细一想貌似不太靠谱,要么改结点结构,要么把结点在第几层存到另外的数据结构中。再一想其实很简单,就像一个递归定义:当前树的minimum depth等于:1.左右子树都不为空时,为子树中较小的minimum depth+1;2.有一 阅读全文
posted @ 2013-11-16 17:34 月窟仙人 阅读(120) 评论(0) 推荐(0) 编辑
摘要: 题目:Given a binary tree, flatten it to a linked list in-place.For example,Given 1 / \ 2 5 / \ \ 3 4 6The flattened tree should look like: 1 \ 2 \ 3 \ 4 \ 5 \ 6其实就是把二叉树按前序遍历顺序以右指针为next搞成一... 阅读全文
posted @ 2013-11-16 02:36 月窟仙人 阅读(121) 评论(0) 推荐(0) 编辑
摘要: leetcode上的题目是这样的:Given a binary tree, find the maximum path sum.The path may start and end at any node in the tree.For example:Given the below binary tree, 1 / \ 2 3Return6.这道题目跟那道求数组里子数组和最大的题目类似,使用的是分治方法,有以下三种情况:对于一个结点,以该结点为根,最大和的路径会出现在1.根的左子树中2.根的右子树中3.包含根的路径,起始与终止结点分别在左、右子树中思路清晰后... 阅读全文
posted @ 2013-11-16 01:32 月窟仙人 阅读(163) 评论(0) 推荐(0) 编辑
摘要: LeetCode上一道题目递归实现后序遍历我在OJ上直接使用了Tag的方法标志是第几次访问结点来区分,代码如下: 1 vector postorderTraversal(TreeNode *root) { 2 // IMPORTANT: Please reset any member data you declared, as 3 // the same Solution instance will be reused for each test case. 4 vector result; 5 if(root==NULL) 6... 阅读全文
posted @ 2013-11-16 00:57 月窟仙人 阅读(151) 评论(0) 推荐(0) 编辑