摘要: 题目Two elements of a binary search tree (BST) are swapped by mistake.Recover the tree without changing its structure.Note:A solution using O(n) space is pretty straight forward. Could you devise a constant space solution?confused what"{1,#,2,3}"means?> read more on how binary tree is ser 阅读全文
posted @ 2013-12-10 22:08 SangS 阅读(1382) 评论(0) 推荐(0) 编辑
摘要: 思路:1. 难点在于构造递归函数的参数2. 参数要包含上下界, 才能具有全局性. 第一次提交 WA 了, 因为写成来的判断函数是局部性的代码:const int POS = 1E9;const int NEG = -1E9;class Solution {public: bool ans; bool isValidBST(TreeNode *root) { if(root == NULL) return true; ans = true; if(root->left) isBST(root->left, NEG, root->val); if(root->right) 阅读全文
posted @ 2013-12-10 21:39 SangS 阅读(222) 评论(0) 推荐(0) 编辑
摘要: 1. 变量属性与继承之间的关系#include using namespace std;class A {public: int x;protected: int y;private: int z;};class B : public A { // x is public // y is protected // z is not accessible from B};class C : protected A { // x is protected // y is protected // z is not accessible from... 阅读全文
posted @ 2013-12-10 19:27 SangS 阅读(1169) 评论(0) 推荐(0) 编辑
摘要: 总结:1. 注意 cnt-- 的位置以及 level push 的位置2. II 在 1 的基础上加个 stack 或者直接 reverse 都可以代码:class Solution {public: vector > levelOrder(TreeNode *root) { vector > res; if(root == NULL) return res; queue record; vector level; int cnt = 1, nextcnt = 0; record.push(root); while(!record.empty()) ... 阅读全文
posted @ 2013-12-10 17:25 SangS 阅读(149) 评论(0) 推荐(0) 编辑
摘要: 总结:1. 第 36 行代码, 最好是按照 len 来遍历, 而不是下标代码: 前序中序#include #include using namespace std;struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} };class Solution {public: vector preorder, inorder; TreeNode *buildTree(vector &preord... 阅读全文
posted @ 2013-12-10 17:04 SangS 阅读(174) 评论(0) 推荐(0) 编辑
摘要: Q: 如何返回一颗子树的最后一个节点?A: 如果有有右子树, 则最右节点在左子树上, 否则在左子树上思路:1. 题目要求转换要 in-place2. 函数 preorder(root) 返回以 root 为根子树的最右节点, 同时完成 flatten 工作代码:代码的逻辑有些乱class Solution {public: void flatten(TreeNode *root) { if(root == NULL) return; preorder(root); } TreeNode* preorder(TreeNode *root) { if(root->... 阅读全文
posted @ 2013-12-10 15:14 SangS 阅读(442) 评论(0) 推荐(0) 编辑