【LeetCode】树(共94题)
【94】Binary Tree Inorder Traversal
【95】Unique Binary Search Trees II (2018年11月14日,算法群)
给了一个 n,返回结点是 1 ~ n 的所有形态的BST。
题解:枚举每个根节点 r, 然后递归的生成左右子树的所有集合,然后做笛卡尔积。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<TreeNode*> generateTrees(int n) {
if (n == ) {return vector<TreeNode*>();}
return generateTrees(, n);
} vector<TreeNode*> generateTrees(int begin, int end) {
vector<TreeNode*> ret;
if (begin > end) {
ret.push_back(nullptr);
return ret;
}
if (begin == end) {
TreeNode* root = new TreeNode(begin);
ret.push_back(root);
return ret;
}
for (int r = begin; r <= end; ++r) {
vector<TreeNode*> leftSon = generateTrees(begin, r - );
vector<TreeNode*> rightSon = generateTrees(r + , end);
for (auto leftEle : leftSon) {
for (auto rightEle : rightSon) {
TreeNode* root = new TreeNode(r);
root->left = leftEle;
root->right = rightEle;
ret.push_back(root);
}
}
}
return ret;
}
};
这题还能用 dp 解答,估计能快点。dp怎么解答看discuss。
【96】Unique Binary Search Trees (2018年11月14日,算法群相关题复习)
给了一个 n, 返回结点是 1 ~ n 的 BST 有多少种形态。
题解:dp, dp[k] 代表 k 个结点的 BST 有多少种形态。dp[0] = 1, dp[1] =1, dp[2] = 2。dp[k] = sigma(dp[left] * dp[k - left - 1]) (0 <= left < k)
class Solution {
public:
int numTrees(int n) {
// f[0] = 1, f[1] = 1, f[2] = 2,
// f[k] = sigma(f[i] * f[k-i-1]) (i belongs [0, k-1])
vector<int> dp(n+, );
dp[] = dp[] = ; dp[] = ;
for (int k = ; k <= n; ++k) {
for (int left = ; left <= k-; ++left) {
int right = k - left - ;
dp[k] += dp[left] * dp[right];
}
}
return dp[n];
}
};
【98】Validate Binary Search Tree
写个函数检查一棵树是不是BST
题解:直接判断左儿子比根小,右儿子比跟大是会WA的... 举个会WA的例子。
【99】Recover Binary Search Tree
【100】Same Tree
【101】Symmetric Tree
【102】Binary Tree Level Order Traversal (2019年1月26日,谷歌tag复习)
二叉树的层级遍历
题解:bfs,这题不上代码。
【103】Binary Tree Zigzag Level Order Traversal (2019年1月26日,谷歌tag复习)
二叉树的层级遍历,zigzag版本
题解:用两个栈,不是用队列了。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
if (!root) {
return vector<vector<int>>();
}
stack<TreeNode*> stk, stk2;
stk.push(root);
vector<vector<int>> ret;
int line = ;
while (!stk.empty()) { //stk: [7, 15]
const int size = stk.size(); // size = 2
vector<int> rows;
for (int i = ; i < size; ++i) {
TreeNode* cur = stk.top(); stk.pop(); //cur = 15, 7
rows.push_back(cur->val); //rows = {15}
if (line & ) { //
if (cur->right) {
stk2.push(cur->right); //stk2 : 7
}
if (cur->left) {
stk2.push(cur->left); //stk2 : 7, 15
}
} else {
if (cur->left) {
stk2.push(cur->left);
}
if (cur->right) {
stk2.push(cur->right);
}
}
}
ret.push_back(rows); //[[3], [20, 9], ]
line ^= ; //line = 0;
swap(stk, stk2); // stk = [7, 15]
}
return ret;
}
};
【104】Maximum Depth of Binary Tree
【105】Construct Binary Tree from Preorder and Inorder Traversal
【106】Construct Binary Tree from Inorder and Postorder Traversal
给中序遍历 和 后序遍历, 重建二叉树。
题解:没啥难度,一次ac
【107】Binary Tree Level Order Traversal II
【108】Convert Sorted Array to Binary Search Tree
给一个增序的vector, 建立一棵高度平衡的BST.
这个题一开始懵了,不会做。。。信不信考到你就挂了orz
思路是二分的思想,从root开始建树,然后左儿子,右儿子。
【110】Balanced Binary Tree (2019年1月26日,谷歌tag复习)
判断一棵树是不是高度平衡的二叉树。
题解:分别判断左儿子和右儿子是不是高度平衡的二叉树。然后判断左儿子的高度和右儿子的高度是否相差小于等于1.
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isBalanced(TreeNode* root) {
if (!root) {return true;}
int leftHeight = getHeight(root->left), rightHeight = getHeight(root->right);
if (abs(leftHeight - rightHeight) > ) {
return false;
}
return isBalanced(root->left) && isBalanced(root->right);
}
int getHeight(TreeNode* root) {
if (!root) { return ;}
if (!root->left && !root->right) {return ;}
return max(getHeight(root->left), getHeight(root->right)) + ;
}
};
【111】Minimum Depth of Binary Tree
【112】Path Sum
【113】Path Sum II
【114】Flatten Binary Tree to Linked List
把一颗二叉树拍平成一个链表。如图。判空,莫忘。要取一个节点的子节点之前,要判断这个节点是否为空。
【116】Populating Next Right Pointers in Each Node (2019年1月26日,谷歌tag复习)
给了一个很特殊的满二叉树的结构,让我们把每层的节点都和它的兄弟/邻居节点连接起来。
题解:我是用了 bfs 来解决这个问题的。
/**
* Definition for binary tree with next pointer.
* struct TreeLinkNode {
* int val;
* TreeLinkNode *left, *right, *next;
* TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
* };
*/
class Solution {
public:
void connect(TreeLinkNode *root) {
if (!root) { return; }
queue<TreeLinkNode* > que;
que.push(root);
while (!que.empty()) {
const int size = que.size();
for (int i = ; i < size; ++i) {
TreeLinkNode* cur = que.front(); que.pop();
if (i == size - ) {
cur->next = nullptr;
} else {
cur->next = que.front();
}
if (cur->left) {
que.push(cur->left);
}
if (cur->right) {
que.push(cur->right);
}
}
}
return;
}
};
【117】Populating Next Right Pointers in Each Node II (2019年1月26日,谷歌tag复习)
本题和116的区别在于,给的树可能不是满二叉树。
题解:还是116的方法可以解。代码同116,一行都不用改。
【124】Binary Tree Maximum Path Sum
【129】Sum Root to Leaf Numbers
【144】Binary Tree Preorder Traversal
【145】Binary Tree Postorder Traversal
【156】Binary Tree Upside Down
【173】Binary Search Tree Iterator
【199】Binary Tree Right Side View
【222】Count Complete Tree Nodes
【226】Invert Binary Tree
【230】Kth Smallest Element in a BST
【235】Lowest Common Ancestor of a Binary Search Tree (2019年1月29日,复习)
返回一棵 bst 的给定两个结点的最小公共祖先。
题解:如果这两个结点的值一个小于等于root,一个大于等于root,那么返回root。否则如果都比root小的话,就递归到左边结点,如果都比root大的话,就递归到右边结点。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if (!root || !p || !q) {return nullptr;}
if (p->val <= root->val && q->val >= root->val || q->val <= root->val && p->val >= root->val) {
return root;
}
if (p->val < root->val && q->val < root->val) {
return lowestCommonAncestor(root->left, p, q);
}
return lowestCommonAncestor(root->right, p, q);
}
};
【236】Lowest Common Ancestor of a Binary Tree (2019年1月29日,复习)
给定一棵任意二叉树和两个结点p,q,返回p,q的最小公共祖先。
题解:比较简单想的一种解法就是从root开始分别做两个dfs,找 p 和 q 的路径,找到之后,返回公共的最后一个结点。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if (!root) {return root;}
vector<TreeNode*> pathP, pathQ;
dfs(root, p, pathP);
dfs(root, q, pathQ);
reverse(pathP.begin(), pathP.end());
reverse(pathQ.begin(), pathQ.end());
TreeNode* res = root;
for (int i = ; i < (int)min(pathP.size(), pathQ.size()); ++i) {
if (pathP[i] == pathQ[i]) {
res = pathP[i];
} else {
break;
}
}
return res;
}
bool dfs(TreeNode* root, TreeNode* p, vector<TreeNode*>& path) {
if (!root) { return false; }
if (root == p || dfs(root->left, p, path) || dfs(root->right, p, path)) {
path.push_back(root);
return true;
}
return false;
}
};
还有一种递归的方法可以做。前提是 p, q这两个结点要保证在二叉树里面。
1. 如果当前node为空,或者等于p,q中的任意一个的话,那么就返回node。
2.分别递归调用node的左右子树,查看返回结果,如果leftRes == null ,就说明两个结点都在右子树里面,返回rightRes,如果rightRes == null, 说明两个结点都在左子树里面,返回leftRes。否则的话,一左一右说明应该返回当前层的node。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if (!root) {return root;}
if (root == p || root == q) {
return root;
}
TreeNode* leftRes = lowestCommonAncestor(root->left, p, q);
TreeNode* rightRes = lowestCommonAncestor(root->right, p, q);
if (!leftRes) {
return rightRes;
}
if (!rightRes) {
return leftRes;
}
return root;
}
};
【250】Count Univalue Subtrees
返回一棵二叉树所有结点值都相同的子树的个数。
题解:叶子结点肯定是 univalue 的子树,如果不是叶子结点,就先判断它的左右儿子是不是 univalue subtree,如果是,在判断根节点和左右儿子结点这三个值是否相等,如果子树都不是 univalue 的了,那么包含根结点的更加不是了。
不要随便在leetcode里面用静态变量,不然一个新的case如果没有重新初始化静态变量就直接在原来case的基础上累加/变化了。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
//如果是叶子结点,就直接+1, 如果不是叶子结点,就判断左右子树是不是uni-value tree,如果是,再判断root和左右儿子的值是否相等,不然如果子树不是 uni-val tree, 那么更大的树也肯定不是 uni-val tree。
class Solution {
public:
int countUnivalSubtrees(TreeNode* root) {
isSameVal(root);
return cnt;
}
bool isSameVal(TreeNode* root) {
if (!root) {return true;}
if (!root->left && !root->right) {
cnt++;
return true;
}
bool leftSame = isSameVal(root->left), rightSame = isSameVal(root->right);
if (!leftSame || !rightSame) {
return false;
}
if (!root->left && root->right && root->right->val == root->val) {
cnt++;
return true;
} else if (!root->right && root->left && root->left->val == root->val) {
cnt++;
return true;
} else if (root->left && root->right) {
if (root->val == root->left->val && root->val == root->right->val) {
cnt++;
return true;
}
}
return false;
}
int cnt = ;
};
【255】Verify Preorder Sequence in Binary Search Tree
【257】Binary Tree Paths
【270】Closest Binary Search Tree Value
【272】Closest Binary Search Tree Value II
【285】Inorder Successor in BST
【297】Serialize and Deserialize Binary Tree
【298】Binary Tree Longest Consecutive Sequence
【333】Largest BST Subtree
【337】House Robber III (谷歌tag,2019年2月9日)
其实老实说我没怎么搞懂?===!!!
【366】Find Leaves of Binary Tree
返回一棵二叉树所有叶子,直到这棵树为空。
题解:我是用 dfs 每次都遍历树的一层叶子,这层搞完之后就把它爹的指向叶子的指针给干掉。时间复杂度起码O(L*2^H) (L是层数,H是整棵树的高度)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int>> findLeaves(TreeNode* root) {
vector<vector<int>> ans;
if (!root) {return ans;}
vector<int> temp;
while (!dfs(root, temp)) {
ans.push_back(temp);
temp.clear();
}
ans.push_back(temp);
return ans;
} bool dfs(TreeNode* root, vector<int>& temp) {
if (!root) {return false;}
if (!root->left && !root->right) {
temp.push_back(root->val);
return true;
}
bool l = dfs(root->left, temp), r = dfs(root->right, temp);
if (l) {
root->left = NULL;
}
if (r) {
root->right = NULL;
}
return false;
} };
PS:这题可能有更加优秀的方法,看我这种遍历了L次根节点的肯定不够优秀。
【404】Sum of Left Leaves (2019年1月29日,easy)
返回一棵二叉树的所有左叶子结点的和。
题解:dfs,分类,分成左儿子,右儿子和根结点。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
return dfs(root, );
}
int dfs(TreeNode* root, int type) {//type: 0 当前结点是根结点, 1 当前结点是父亲结点的左儿子, 2 当前结点是父亲结点的右儿子
int ret = ;
if (!root) {return ret;}
if (root->left) {
ret += dfs(root->left, );
}
if (root->right) {
ret += dfs(root->right, );
}
if (!root->left && !root->right && type == ) {
ret += root->val;
}
return ret;
}
};
【426】Convert Binary Search Tree to Sorted Doubly Linked List
【428】Serialize and Deserialize N-ary Tree
【429】N-ary Tree Level Order Traversal
【431】Encode N-ary Tree to Binary Tree
【437】Path Sum III (2019年2月11日)
本题是 112,113 的进阶版本。给了一棵二叉树,和一个值 sum,返回树上有多少条路径的和等于 sum,路径的开始和结束不要求是根结点和叶子结点。
题解:利用一个辅助数组标记当前这条path的前缀和。当前结点的前缀和 - 前面某个结点的前缀和 == sum, res++
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int pathSum(TreeNode* root, int sum) {
if (!root) {return ;}
vector<int> path{};
dfs(root, path, sum);
return res;
}
int res = ;
void dfs(TreeNode* root, vector<int>& path, const int sum) {
if (!root) {return; }
int num = root->val;
if (!path.empty()) {num += path.back();}
for (auto val : path) {
if (num - val == sum) { res++; }
}
path.push_back(num);
dfs(root->left, path, sum);
dfs(root->right, path, sum);
path.pop_back();
}
};
【449】Serialize and Deserialize BST
【450】Delete Node in a BST (2019年2月16日)
删除BST的一个指定结点,结点的key作为输入。
题解:先递归找到这个结点,然后如果这个结点的左儿子,右儿子有一个为空结点的话, 那么把另外一个儿子提上来。如果没有左右儿子,那么就返回nullptr,如果两个儿子都有的话,那么找到左儿子的最大值,递归删除左儿子的最大值,然后把自己的值替换成左儿子的最大值。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* deleteNode(TreeNode* root, int key) {
if (!root) {return root;}
if (key < root->val) {
root->left = deleteNode(root->left, key);
return root;
}
if (key > root->val) {
root->right = deleteNode(root->right, key);
return root;
}
if (root->left && !root->right) {
return root->left;
} else if (!root->left && root->right) {
return root->right;
} else if (!root->left && !root->right) {
return nullptr;
}
int leftMax = findMax(root->left);
root->left = deleteNode(root->left, leftMax);
root->val = leftMax;
return root;
}
int findMax(TreeNode* root) {
if (!root) {return -;}
int res = root->val;
if (root->right) {
res = findMax(root->right);
}
return res;
}
};
【501】Find Mode in Binary Search Tree (2018年11月24日,冲刺题量)
给了一个有重复结点的BST,返回出现频率最高的结点是值的数组。
题解:我直接 dfs 了一下BST,用 map 保存每个结点出现了多少次。暴力解法。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> findMode(TreeNode* root) {
dfs(root);
vector<int> ret;
for (auto ele : mp) {
if (ele.second == mostFreq) {
ret.push_back(ele.first);
}
}
return ret;
}
void dfs(TreeNode* root) {
if (!root) {return;}
if (root->left) {
dfs(root->left);
}
mp[root->val]++;
mostFreq = max(mp[root->val], mostFreq);
if (root->right) {
dfs(root->right);
}
return;
}
map<int, int> mp;
int mostFreq = ;
};
本题我估计还有别的解法,给了 BST 的性质完全没有用到。==。。
【508】Most Frequent Subtree Sum
【513】Find Bottom Left Tree Value
【515】Find Largest Value in Each Tree Row
【536】Construct Binary Tree from String (2019年2月15日)
给了一个string,由数字,括号组成,重构二叉树。
Input: "4(2(3)(1))(6(5))"
Output: return the tree root node representing the following tree: 4
/ \
2 6
/ \ /
3 1 5
题解:递归。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* str2tree(string s) {
if (s.empty()) {return nullptr;}
int left = , right = , num = ;
string strLeft, strRight;
int preIdx = -;
for (int i = ; i < s.size(); ++i) {
if (left == && right == && isdigit(s[i])) {
num = num * + (s[i] - '');
preIdx = i;
} else if (s[i] == '(') {
left++;
} else if (s[i] == ')') {
right++;
}
if (left == right && left != ) {
strLeft = s.substr(preIdx + , i - preIdx);
strRight = s.substr(i + );
break;
}
}
if (s[] == '-') {num = -num;}
TreeNode * root = new TreeNode(num);
if (!strLeft.empty()) {
root->left = str2tree(strLeft.substr(, strLeft.size()-));
}
if (!strRight.empty()) {
root->right = str2tree(strRight.substr(, strRight.size()-));
}
return root;
}
};
【538】Convert BST to Greater Tree (2018年11月14日,冲刺题量)
给了一棵 BST,把这棵树变成 greater tree。变换方法是把一个结点的值变成这个结点原来的值,加上所有比这个结点值大的结点的和。
题解:我们考虑这棵 BST 的最右边的叶子结点肯定还是原来的值。然后我们用一个 summ 记录比当前结点大的所有结点的和。然后 dfs 这棵树,顺序就是 right -> root -> left.
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
//right -> root -> left
TreeNode* convertBST(TreeNode* root) {
int summ = ;
dfs(root, summ);
return root;
}
void dfs(TreeNode* root, int& summ) {
if (!root) { return; }
dfs(root->right, summ);
root->val += summ;
summ = root->val;
dfs(root->left, summ);
return;
}
};
【543】Diameter of Binary Tree (2018年11月14日,为了冲点题量)
给了一棵二叉树,问二叉树的直径多少。直径的定义是从一个结点到另外一个结点的最长距离。
题解:这个最长距离可能出现在哪里?一个结点的孩子结点作为根节点的子树的直径,或者这个结点自己做根的直径。(代码写的有点乱,但是还是过了orz)。(本题应该还有更快的方法,要看。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int diameterOfBinaryTree(TreeNode* root) {
if (!root) {return ;}
int leftres = diameterOfBinaryTree(root->left);
int rightres = diameterOfBinaryTree(root->right);
int tempres = max(leftres, rightres);
int selfres = getPathLen(root->left) + + getPathLen(root->right) + ;
tempres = max(selfres, tempres);
globalMax = max(tempres, globalMax);
return globalMax;
}
int getPathLen(TreeNode* root) {
if (!root) {return -;}
if (pathLen.find(root) != pathLen.end()) {return pathLen[root];}
if (!root->left && !root->right) {
pathLen[root] == ;
return ;
}
pathLen[root] = max(getPathLen(root->left), getPathLen(root->right)) + ;
return pathLen[root];
}
int globalMax = ;
unordered_map<TreeNode*, int> pathLen;
};
【545】Boundary of Binary Tree
【549】Binary Tree Longest Consecutive Sequence II
【559】Maximum Depth of N-ary Tree
【563】Binary Tree Tilt
【572】Subtree of Another Tree
【582】Kill Process
【589】N-ary Tree Preorder Traversal (2018年11月14日,为了冲点题量)
给了一个 N叉树,返回它的先序遍历。
题解:直接dfs。
/*
// Definition for a Node.
class Node {
public:
int val;
vector<Node*> children; Node() {} Node(int _val, vector<Node*> _children) {
val = _val;
children = _children;
}
};
*/
class Solution {
public:
vector<int> preorder(Node* root) {
vector<int> ret;
if (!root) {return ret;}
preorder(root, ret);
return ret;
}
void preorder(Node* root, vector<int>& ret) {
ret.push_back(root->val);
for (auto kid : root->children) {
preorder(kid, ret);
}
return;
} };
本题有个follow-up, 问能不能写个 iteratively 的代码。还没做。
【590】N-ary Tree Postorder Traversal (2018年11月14日,为了冲点题量)
给了一个 N 叉树,返回它的后序遍历。
题解:直接dfs。
/*
// Definition for a Node.
class Node {
public:
int val;
vector<Node*> children; Node() {} Node(int _val, vector<Node*> _children) {
val = _val;
children = _children;
}
};
*/
class Solution {
public:
vector<int> postorder(Node* root) {
vector<int> ret;
if (!root) {return ret;}
postorder(root, ret);
return ret;
}
void postorder(Node* root, vector<int>& ret) {
if (!root) {return;}
for (auto kid : root->children) {
postorder(kid, ret);
}
ret.push_back(root->val);
return;
}
};
follow-up还是能不能写 iteratively 的代码,依旧还没看。
【606】Construct String from Binary Tree (2018年11月14日,为了冲点题量,这题以前还写错了,这次一次过了orz)
从给定的二叉树中形成一个字符串,返回字符串。省略不必要的括号,比如叶子结点下面的空结点。或者如果一个结点有左儿子,没有右儿子,那么他右儿子的括号可以省略,但是如果他有右儿子,没有左儿子,那么左儿子括号不能省略。
Example :
Input: Binary tree: [,,,] / \ / Output: "1(2(4))(3)"
Explanation: Originallay it needs to be "1(2(4)())(3()())",
but you need to omit all the unnecessary empty parenthesis pairs.
And it will be "1(2(4))(3)". Example :
Input: Binary tree: [,,,null,] / \ \ Output: "1(2()(4))(3)"
Explanation: Almost the same as the first example,
except we can't omit the first parenthesis pair to break the one-to-one mapping relationship between the input and the output.
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
string tree2str(TreeNode* t) {
if (!t) {return "";}
string strLeft = tree2str(t->left);
string strRight = tree2str(t->right);
string ret = "";
ret = to_string(t->val);
if (!strLeft.empty()) {
ret += "(" + strLeft + ")";
}
if(!strRight.empty()) {
if (strLeft.empty()) {
ret += "()(" + strRight + ")";
} else {
ret += "(" + strRight + ")";
}
}
return ret;
}
};
【617】Merge Two Binary Trees
【623】Add One Row to Tree
【637】Average of Levels in Binary Tree (2018年11月27日)
返回一棵二叉树每层的平均值。
Example 1:
Input:
3
/ \
9 20
/ \
15 7
Output: [3, 14.5, 11]
Explanation:
The average value of nodes on level 0 is 3, on level 1 is 14.5, and on level 2 is 11. Hence return [3, 14.5, 11].
题解:bfs,每层求和,然后求平均值。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<double> averageOfLevels(TreeNode* root) {
vector<double> ret;
if (!root) {return ret;}
queue<TreeNode*> que;
que.push(root);
while (!que.empty()) {
int size = que.size();
double summ = 0.0;
for (int i = ; i < size; ++i) {
TreeNode* cur = que.front(); que.pop();
summ += cur->val;
if (cur->left) {
que.push(cur->left);
}
if (cur->right) {
que.push(cur->right);
}
}
ret.push_back(summ / size);
summ = 0.0;
}
return ret;
}
};
【652】Find Duplicate Subtrees
【653】Two Sum IV - Input is a BST
【654】Maximum Binary Tree (2018年11月27日)
Given an integer array with no duplicates. A maximum tree building on this array is defined as follow:
- The root is the maximum number in the array.
- The left subtree is the maximum tree constructed from left part subarray divided by the maximum number.
- The right subtree is the maximum tree constructed from right part subarray divided by the maximum number.
Construct the maximum tree by the given array and output the root node of this tree.
Input: [3,2,1,6,0,5]
Output: return the tree root node representing the following tree: 6
/ \
3 5
\ /
2 0
\
1
题解:递归求解
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
const int n = nums.size();
if (n == ) {return nullptr;}
int maxValue = nums[], maxIdx = ;
for (int i = ; i < n; ++i) {
if (nums[i] > maxValue) {
maxIdx = i;
maxValue = nums[i];
}
}
TreeNode* root = new TreeNode(maxValue);
vector<int> LeftSon(nums.begin(), nums.begin()+maxIdx);
vector<int> RightSon(nums.begin() + maxIdx + , nums.end());
root->left = constructMaximumBinaryTree(LeftSon);
root->right = constructMaximumBinaryTree(RightSon);
return root;
}
};
【655】Print Binary Tree
【662】Maximum Width of Binary Tree
【663】Equal Tree Partition
【666】Path Sum IV
【669】Trim a Binary Search Tree (2019年2月12日)
给了一棵BST,和一个闭区间[L, R], 要 trim 这颗树,返回只在给定区间内的结点的BST。
题解:递归。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* trimBST(TreeNode* root, int L, int R) {
if (!root) {return root;}
if (R < root->val) { return trimBST(root->left, L, R); }
if (L > root->val) { return trimBST(root->right, L, R); }
root->left = trimBST(root->left, L, R);
root->right = trimBST(root->right, L, R);
return root;
}
};
【671】Second Minimum Node In a Binary Tree
【684】Redundant Connection
【685】Redundant Connection II
【687】Longest Univalue Path
【700】Search in a Binary Search Tree
【701】Insert into a Binary Search Tree (2018年11月25日)
给一棵 BST 里面插入一个值为 val 的结点。
题解:直接递归插入。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* insertIntoBST(TreeNode* root, int val) {
if (!root) {
root = new TreeNode(val);
return root;
}
if (root->val > val) {
if (root->left) {
root->left = insertIntoBST(root->left, val);
} else {
root->left = new TreeNode(val);
}
} else if (root->val < val) {
if (root->right) {
root->right = insertIntoBST(root->right, val);
} else {
root->right = new TreeNode(val);
}
}
return root;
}
};
【742】Closest Leaf in a Binary Tree
【814】Binary Tree Pruning (2018年11月27日)
给一棵二叉树剪枝,把全 0 的子树全部减没。返回新的根节点。
题解:直接递归做吧,第一次提交 WA 了一次。因为没考虑清楚先递归处理子树,还是先处理本身。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* pruneTree(TreeNode* root) {
if (!root) {return root;}
if (root->left) {
root->left = pruneTree(root->left);
TreeNode* node = root->left;
if (!node->left && !node->right && node->val == ) {
root->left = nullptr;
}
}
if (root->right) {
root->right = pruneTree(root->right);
TreeNode* node = root->right;
if (!node->left && !node->right && node->val == ) {
root->right = nullptr;
}
}
return root;
}
};
【834】Sum of Distances in Tree
【863】All Nodes Distance K in Binary Tree
【865】Smallest Subtree with all the Deepest Nodes
【872】Leaf-Similar Trees
【889】Construct Binary Tree from Preorder and Postorder Traversal
【894】All Possible Full Binary Trees
【897】Increasing Order Search Tree (2019年2月10日,算法群打卡)
给了一棵BST,重新排布树上的结点,使得树上最左边的叶子结点是它的根,然后树上的每个结点都没有左子树,只有一个右儿子。
题解:我们的目标是 res = inorder(root.left) + root + inorder(root.right),所以递归就行了,传入一个tail指针。注意这个题不能重新搞一棵树出来,需要rearrange。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* increasingBST(TreeNode* root, TreeNode* tail = nullptr) {
if (!root) {return tail;}
TreeNode* ret = increasingBST(root->left, root);
root->left = nullptr;
root->right = increasingBST(root->right, tail);
return ret;
}
};
【LeetCode】树(共94题)的更多相关文章
- 【sql】leetcode习题 (共 42 题)
[175]Combine Two Tables (2018年11月23日,开始集中review基础) Table: Person +-------------+---------+ | Column ...
- Leetcode 简略题解 - 共567题
Leetcode 简略题解 - 共567题 写在开头:我作为一个老实人,一向非常反感骗赞.收智商税两种行为.前几天看到不止两三位用户说自己辛苦写了干货,结果收藏数是点赞数的三倍有余,感觉自己的 ...
- LeetCode面试常见100题( TOP 100 Liked Questions)
LeetCode面试常见100题( TOP 100 Liked Questions) 置顶 2018年07月16日 11:25:22 lanyu_01 阅读数 9704更多 分类专栏: 面试编程题真题 ...
- LeetCode树专题
LeetCode树专题 98. 验证二叉搜索树 二叉搜索树,每个结点的值都有一个范围 /** * Definition for a binary tree node. * struct TreeNod ...
- HDU 4578 Transformation --线段树,好题
题意: 给一个序列,初始全为0,然后有4种操作: 1. 给区间[L,R]所有值+c 2.给区间[L,R]所有值乘c 3.设置区间[L,R]所有值为c 4.查询[L,R]的p次方和(1<=p< ...
- Hihicoder 题目1 : Trie树(字典树,经典题)
题目1 : Trie树 时间限制:10000ms 单点时限:1000ms 内存限制:256MB 描述 小Hi和小Ho是一对好朋友,出生在信息化社会的他们对编程产生了莫大的兴趣,他们约定好互相帮助,在编 ...
- poj 3264:Balanced Lineup(线段树,经典题)
Balanced Lineup Time Limit: 5000MS Memory Limit: 65536K Total Submissions: 32820 Accepted: 15447 ...
- poj 2503:Babelfish(字典树,经典题,字典翻译)
Babelfish Time Limit: 3000MS Memory Limit: 65536K Total Submissions: 30816 Accepted: 13283 Descr ...
- poj 2001:Shortest Prefixes(字典树,经典题,求最短唯一前缀)
Shortest Prefixes Time Limit: 1000MS Memory Limit: 30000K Total Submissions: 12731 Accepted: 544 ...
随机推荐
- /usr,/usr/local/ 还是 /opt 目录区别
Linux 的软件安装目录是也是有讲究的,理解这一点,在对系统管理是有益的 /us(Unix Software Resource)r:系统级的目录,可以理解为C:/Windows/, /usr/lib ...
- nginx之访问静态文件
如何配置nginx,访问服务器上的静态文件? 1.在目录/data/interface_test下创建静态文件queryAppData.json,内容如下: 如何访问该文件呢? 2.修改/usr/lo ...
- 20180716-Java正则表达式
import java.util.regex.Matcher;import java.util.regex.Pattern; public class RegexMatches{ public sta ...
- scau 1079 三角形(暴力)
</pre>1079 三角形</h1></center><p align="center" style="margin-top: ...
- 【MEAN Web开发】CentOS 7 安装MongoDB 3.2.3
偶然得了一本书,AmosQ.Haviv 所著 <MEAN Web开发>.起初并不知道这啥东西,看了下目录发现正好有讲MongoDB而已.当时的项目正好需要做MongoDB的内容,之后这书就 ...
- Oracle_管理控制文件和日志文件
控制文件: 控制文件在数据库创建时被自动创建,并在数据库发生物理变化时更新.控制文件被不断更新,并且在任何时候都要保证控制文件是可用的.只有Oracle进程才能安全地更新控制文件的内容,所以,任何时候 ...
- 测开之路七十二:性能测试工具之locust简介
locust官网:https://locust.io/ locust安装(不支持python3.7):pip install locustio 或者pycharm安装 官网给出的样例 根据官网代码 ...
- 2017/2/27-Laravel_资源控制器命令
用于处理关于图片存储的 HTTP 请求,使用 Artisan 命令 make:controller,我们可以快速创建这样的控制器 : php artisan make:controller Photo ...
- 001/Nginx高可用模式下的负载均衡与动静分离(笔记)
Nginx高可用模式下的负载均衡与动静分离 Nginx(engine x)是一个高性能的HTTP和反向代理服务器,具有内存少,并发能力强特点. 1.处理静态文件.索引文件以及自动索引:打开文件描述符缓 ...
- 12.定义Lock类,用于锁定数据.三步走,锁的优缺点
#在threading模块当中定义了一个Lock类,可以方便的使用锁定: # #1.创建锁 # mutex = threading.Lock() # # #2.锁定 ''' mutex.acquire ...