【LeetCode】树(共94题)

【94】Binary Tree Inorder Traversal

【95】Unique Binary Search Trees II (2018年11月14日,算法群)

给了一个 n,返回结点是 1 ~ n 的所有形态的BST。

题解:枚举每个根节点 r, 然后递归的生成左右子树的所有集合,然后做笛卡尔积。

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     vector<TreeNode*> generateTrees(int n) {
13         if (n == 0) {return vector<TreeNode*>();}
14         return generateTrees(1, n);
15     }
16
17     vector<TreeNode*> generateTrees(int begin, int end) {
18         vector<TreeNode*> ret;
19         if (begin > end) {
20             ret.push_back(nullptr);
21             return ret;
22         }
23         if (begin == end) {
24             TreeNode* root = new TreeNode(begin);
25             ret.push_back(root);
26             return ret;
27         }
28         for (int r = begin; r <= end; ++r) {
29             vector<TreeNode*> leftSon = generateTrees(begin, r - 1);
30             vector<TreeNode*> rightSon = generateTrees(r + 1, end);
31             for (auto leftEle : leftSon) {
32                 for (auto rightEle : rightSon) {
33                     TreeNode* root = new TreeNode(r);
34                     root->left = leftEle;
35                     root->right = rightEle;
36                     ret.push_back(root);
37                 }
38             }
39         }
40         return ret;
41     }
42 };

这题还能用 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)

 1 class Solution {
 2 public:
 3     int numTrees(int n) {
 4         // f[0] = 1, f[1] = 1, f[2] = 2,
 5         // f[k] = sigma(f[i] * f[k-i-1]) (i belongs [0, k-1])
 6         vector<int> dp(n+1, 0);
 7         dp[0] = dp[1] = 1; dp[2] = 2;
 8         for (int k = 3; k <= n; ++k) {
 9             for (int left = 0; left <= k-1; ++left) {
10                 int right = k - left - 1;
11                 dp[k] += dp[left] * dp[right];
12             }
13         }
14         return dp[n];
15     }
16 };

【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版本

题解:用两个栈,不是用队列了。

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
13         if (!root) {
14             return vector<vector<int>>();
15         }
16         stack<TreeNode*> stk, stk2;
17         stk.push(root);
18         vector<vector<int>> ret;
19         int line = 0;
20         while (!stk.empty()) {  //stk: [7, 15]
21             const int size = stk.size(); // size = 2
22             vector<int> rows;
23             for (int i = 0; i < size; ++i) {
24                 TreeNode* cur = stk.top(); stk.pop(); //cur = 15, 7
25                 rows.push_back(cur->val); //rows = {15}
26                 if (line & 1) { //
27                     if (cur->right) {
28                         stk2.push(cur->right); //stk2 : 7
29                     }
30                     if (cur->left) {
31                         stk2.push(cur->left); //stk2 : 7, 15
32                     }
33                 } else {
34                     if (cur->left) {
35                         stk2.push(cur->left);
36                     }
37                     if (cur->right) {
38                         stk2.push(cur->right);
39                     }
40                 }
41             }
42             ret.push_back(rows);  //[[3], [20, 9], ]
43             line ^= 1; //line = 0;
44             swap(stk, stk2); // stk = [7, 15]
45         }
46         return ret;
47     }
48 };

【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.

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     bool isBalanced(TreeNode* root) {
13         if (!root) {return true;}
14         int leftHeight = getHeight(root->left), rightHeight = getHeight(root->right);
15         if (abs(leftHeight - rightHeight) > 1) {
16             return false;
17         }
18         return isBalanced(root->left) && isBalanced(root->right);
19     }
20     int getHeight(TreeNode* root) {
21         if (!root) { return 0;}
22         if (!root->left && !root->right) {return 1;}
23         return max(getHeight(root->left), getHeight(root->right)) + 1;
24     }
25 };

【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 来解决这个问题的。

 1 /**
 2  * Definition for binary tree with next pointer.
 3  * struct TreeLinkNode {
 4  *  int val;
 5  *  TreeLinkNode *left, *right, *next;
 6  *  TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     void connect(TreeLinkNode *root) {
12         if (!root) { return; }
13         queue<TreeLinkNode* > que;
14         que.push(root);
15         while (!que.empty()) {
16             const int size = que.size();
17             for (int i = 0; i < size; ++i) {
18                 TreeLinkNode* cur = que.front(); que.pop();
19                 if (i == size - 1) {
20                     cur->next = nullptr;
21                 } else {
22                     cur->next = que.front();
23                 }
24                 if (cur->left) {
25                     que.push(cur->left);
26                 }
27                 if (cur->right) {
28                     que.push(cur->right);
29                 }
30             }
31         }
32         return;
33     }
34 };

【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

【236】Lowest Common Ancestor of a Binary Tree

【250】Count Univalue Subtrees

返回一棵二叉树所有结点值都相同的子树的个数。

题解:叶子结点肯定是 univalue 的子树,如果不是叶子结点,就先判断它的左右儿子是不是 univalue subtree,如果是,在判断根节点和左右儿子结点这三个值是否相等,如果子树都不是 univalue 的了,那么包含根结点的更加不是了。

不要随便在leetcode里面用静态变量,不然一个新的case如果没有重新初始化静态变量就直接在原来case的基础上累加/变化了。

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 //如果是叶子结点,就直接+1, 如果不是叶子结点,就判断左右子树是不是uni-value tree,如果是,再判断root和左右儿子的值是否相等,不然如果子树不是 uni-val tree, 那么更大的树也肯定不是 uni-val tree。
11 class Solution {
12 public:
13     int countUnivalSubtrees(TreeNode* root) {
14         isSameVal(root);
15         return cnt;
16     }
17     bool isSameVal(TreeNode* root) {
18         if (!root) {return true;}
19         if (!root->left && !root->right) {
20             cnt++;
21             return true;
22         }
23         bool leftSame = isSameVal(root->left), rightSame = isSameVal(root->right);
24         if (!leftSame || !rightSame) {
25             return false;
26         }
27         if (!root->left && root->right && root->right->val == root->val) {
28             cnt++;
29             return true;
30         } else if (!root->right && root->left && root->left->val == root->val) {
31             cnt++;
32             return true;
33         } else if (root->left && root->right) {
34             if (root->val == root->left->val && root->val == root->right->val) {
35                 cnt++;
36                 return true;
37             }
38         }
39         return false;
40     }
41     int cnt = 0;
42 };

【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

【366】Find Leaves of Binary Tree

返回一棵二叉树所有叶子,直到这棵树为空。

题解:我是用 dfs 每次都遍历树的一层叶子,这层搞完之后就把它爹的指向叶子的指针给干掉。时间复杂度起码O(L*2^H) (L是层数,H是整棵树的高度)

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     vector<vector<int>> findLeaves(TreeNode* root) {
13         vector<vector<int>> ans;
14         if (!root) {return ans;}
15         vector<int> temp;
16         while (!dfs(root, temp)) {
17             ans.push_back(temp);
18             temp.clear();
19         }
20         ans.push_back(temp);
21         return ans;
22     }
23
24     bool dfs(TreeNode* root, vector<int>& temp) {
25         if (!root) {return false;}
26         if (!root->left && !root->right) {
27             temp.push_back(root->val);
28             return true;
29         }
30         bool l = dfs(root->left, temp), r = dfs(root->right, temp);
31         if (l) {
32             root->left = NULL;
33         }
34         if (r) {
35             root->right = NULL;
36         }
37         return false;
38     }
39
40 };

PS:这题可能有更加优秀的方法,看我这种遍历了L次根节点的肯定不够优秀。

【404】Sum of Left Leaves (2019年1月29日,easy)

返回一棵二叉树的所有左叶子结点的和。

题解:dfs,分类,分成左儿子,右儿子和根结点。

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     int sumOfLeftLeaves(TreeNode* root) {
13         return dfs(root, 0);
14     }
15     int dfs(TreeNode* root, int type) {//type: 0 当前结点是根结点, 1 当前结点是父亲结点的左儿子, 2 当前结点是父亲结点的右儿子
16         int ret = 0;
17         if (!root) {return ret;}
18         if (root->left) {
19             ret += dfs(root->left, 1);
20         }
21         if (root->right) {
22             ret += dfs(root->right, 2);
23         }
24         if (!root->left && !root->right && type == 1) {
25             ret += root->val;
26         }
27         return ret;
28     }
29 };

【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

【449】Serialize and Deserialize BST

【450】Delete Node in a BST

【501】Find Mode in Binary Search Tree (2018年11月24日,冲刺题量)

给了一个有重复结点的BST,返回出现频率最高的结点是值的数组。

题解:我直接 dfs 了一下BST,用 map 保存每个结点出现了多少次。暴力解法。

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     vector<int> findMode(TreeNode* root) {
13         dfs(root);
14         vector<int> ret;
15         for (auto ele : mp) {
16             if (ele.second == mostFreq) {
17                 ret.push_back(ele.first);
18             }
19         }
20         return ret;
21     }
22     void dfs(TreeNode* root) {
23         if (!root) {return;}
24         if (root->left) {
25             dfs(root->left);
26         }
27         mp[root->val]++;
28         mostFreq = max(mp[root->val], mostFreq);
29         if (root->right) {
30             dfs(root->right);
31         }
32         return;
33     }
34     map<int, int> mp;
35     int mostFreq = 0;
36 };

本题我估计还有别的解法,给了 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

【538】Convert BST to Greater Tree (2018年11月14日,冲刺题量)

给了一棵 BST,把这棵树变成 greater tree。变换方法是把一个结点的值变成这个结点原来的值,加上所有比这个结点值大的结点的和。

题解:我们考虑这棵 BST 的最右边的叶子结点肯定还是原来的值。然后我们用一个 summ 记录比当前结点大的所有结点的和。然后 dfs 这棵树,顺序就是 right -> root -> left.

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     //right -> root -> left
13     TreeNode* convertBST(TreeNode* root) {
14         int summ = 0;
15         dfs(root, summ);
16         return root;
17     }
18     void dfs(TreeNode* root, int& summ) {
19         if (!root) { return; }
20         dfs(root->right, summ);
21         root->val += summ;
22         summ = root->val;
23         dfs(root->left, summ);
24         return;
25     }
26 };

【543】Diameter of Binary Tree (2018年11月14日,为了冲点题量)

给了一棵二叉树,问二叉树的直径多少。直径的定义是从一个结点到另外一个结点的最长距离。

题解:这个最长距离可能出现在哪里?一个结点的孩子结点作为根节点的子树的直径,或者这个结点自己做根的直径。(代码写的有点乱,但是还是过了orz)。(本题应该还有更快的方法,要看。

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     int diameterOfBinaryTree(TreeNode* root) {
13         if (!root) {return 0;}
14         int leftres = diameterOfBinaryTree(root->left);
15         int rightres = diameterOfBinaryTree(root->right);
16         int tempres = max(leftres, rightres);
17         int selfres = getPathLen(root->left) + 1 + getPathLen(root->right) + 1;
18         tempres = max(selfres, tempres);
19         globalMax = max(tempres, globalMax);
20         return globalMax;
21     }
22     int getPathLen(TreeNode* root) {
23         if (!root) {return -1;}
24         if (pathLen.find(root) != pathLen.end()) {return pathLen[root];}
25         if (!root->left && !root->right) {
26             pathLen[root] == 0;
27             return 0;
28         }
29         pathLen[root] = max(getPathLen(root->left), getPathLen(root->right)) + 1;
30         return pathLen[root];
31     }
32     int globalMax = 0;
33     unordered_map<TreeNode*, int> pathLen;
34 };

【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。

 1 /*
 2 // Definition for a Node.
 3 class Node {
 4 public:
 5     int val;
 6     vector<Node*> children;
 7
 8     Node() {}
 9
10     Node(int _val, vector<Node*> _children) {
11         val = _val;
12         children = _children;
13     }
14 };
15 */
16 class Solution {
17 public:
18     vector<int> preorder(Node* root) {
19         vector<int> ret;
20         if (!root) {return ret;}
21         preorder(root, ret);
22         return ret;
23     }
24     void preorder(Node* root, vector<int>& ret) {
25         ret.push_back(root->val);
26         for (auto kid : root->children) {
27             preorder(kid, ret);
28         }
29         return;
30     }
31
32 };

本题有个follow-up, 问能不能写个 iteratively 的代码。还没做。

【590】N-ary Tree Postorder Traversal (2018年11月14日,为了冲点题量)

给了一个 N 叉树,返回它的后序遍历。

题解:直接dfs。

 1 /*
 2 // Definition for a Node.
 3 class Node {
 4 public:
 5     int val;
 6     vector<Node*> children;
 7
 8     Node() {}
 9
10     Node(int _val, vector<Node*> _children) {
11         val = _val;
12         children = _children;
13     }
14 };
15 */
16 class Solution {
17 public:
18     vector<int> postorder(Node* root) {
19         vector<int> ret;
20         if (!root) {return ret;}
21         postorder(root, ret);
22         return ret;
23     }
24     void postorder(Node* root, vector<int>& ret) {
25         if (!root) {return;}
26         for (auto kid : root->children) {
27             postorder(kid, ret);
28         }
29         ret.push_back(root->val);
30         return;
31     }
32 };

follow-up还是能不能写 iteratively 的代码,依旧还没看。

【606】Construct String from Binary Tree (2018年11月14日,为了冲点题量,这题以前还写错了,这次一次过了orz)

从给定的二叉树中形成一个字符串,返回字符串。省略不必要的括号,比如叶子结点下面的空结点。或者如果一个结点有左儿子,没有右儿子,那么他右儿子的括号可以省略,但是如果他有右儿子,没有左儿子,那么左儿子括号不能省略。

Example 1:
Input: Binary tree: [1,2,3,4]
       1
     /       2     3
   /
  4     

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 2:
Input: Binary tree: [1,2,3,null,4]
       1
     /       2     3
     \
      4 

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.

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     string tree2str(TreeNode* t) {
13         if (!t) {return "";}
14         string strLeft = tree2str(t->left);
15         string strRight = tree2str(t->right);
16         string ret = "";
17         ret = to_string(t->val);
18         if (!strLeft.empty()) {
19             ret += "(" + strLeft + ")";
20         }
21         if(!strRight.empty()) {
22             if (strLeft.empty()) {
23                 ret += "()("  + strRight + ")";
24             } else {
25                 ret += "(" + strRight + ")";
26             }
27         }
28         return ret;
29     }
30 };

【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,每层求和,然后求平均值。

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     vector<double> averageOfLevels(TreeNode* root) {
13         vector<double> ret;
14         if (!root) {return ret;}
15         queue<TreeNode*> que;
16         que.push(root);
17         while (!que.empty()) {
18             int size = que.size();
19             double summ = 0.0;
20             for (int i = 0; i < size; ++i) {
21                 TreeNode* cur = que.front(); que.pop();
22                 summ += cur->val;
23                 if (cur->left) {
24                     que.push(cur->left);
25                 }
26                 if (cur->right) {
27                     que.push(cur->right);
28                 }
29             }
30             ret.push_back(summ / size);
31             summ = 0.0;
32         }
33         return ret;
34     }
35 };

【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:

  1. The root is the maximum number in the array.
  2. The left subtree is the maximum tree constructed from left part subarray divided by the maximum number.
  3. 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

题解:递归求解

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
13         const int n = nums.size();
14         if (n == 0) {return nullptr;}
15         int maxValue = nums[0], maxIdx = 0;
16         for (int i = 1; i < n; ++i) {
17             if (nums[i] > maxValue) {
18                 maxIdx = i;
19                 maxValue = nums[i];
20             }
21         }
22         TreeNode* root = new TreeNode(maxValue);
23         vector<int> LeftSon(nums.begin(), nums.begin()+maxIdx);
24         vector<int> RightSon(nums.begin() + maxIdx + 1, nums.end());
25         root->left = constructMaximumBinaryTree(LeftSon);
26         root->right = constructMaximumBinaryTree(RightSon);
27         return root;
28     }
29 };

【655】Print Binary Tree

【662】Maximum Width of Binary Tree

【663】Equal Tree Partition

【666】Path Sum IV

【669】Trim a Binary Search Tree

【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 的结点。

题解:直接递归插入。

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     TreeNode* insertIntoBST(TreeNode* root, int val) {
13         if (!root) {
14             root = new TreeNode(val);
15             return root;
16         }
17         if (root->val > val) {
18             if (root->left) {
19                 root->left = insertIntoBST(root->left, val);
20             } else {
21                 root->left = new TreeNode(val);
22             }
23         } else if (root->val < val) {
24             if (root->right) {
25                 root->right = insertIntoBST(root->right, val);
26             } else {
27                 root->right = new TreeNode(val);
28             }
29         }
30         return root;
31     }
32 };

【742】Closest Leaf in a Binary Tree

【814】Binary Tree Pruning (2018年11月27日)

给一棵二叉树剪枝,把全 0 的子树全部减没。返回新的根节点。

题解:直接递归做吧,第一次提交 WA 了一次。因为没考虑清楚先递归处理子树,还是先处理本身。

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     TreeNode* pruneTree(TreeNode* root) {
13         if (!root) {return root;}
14         if (root->left) {
15             root->left = pruneTree(root->left);
16             TreeNode* node = root->left;
17             if (!node->left && !node->right && node->val == 0) {
18                 root->left = nullptr;
19             }
20         }
21         if (root->right) {
22             root->right = pruneTree(root->right);
23             TreeNode* node = root->right;
24             if (!node->left && !node->right && node->val == 0) {
25                 root->right = nullptr;
26             }
27         }
28         return root;
29     }
30 };

【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

p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px Helvetica }

原文地址:https://www.cnblogs.com/zhangwanying/p/6753328.html

时间: 2024-10-17 08:04:57

【LeetCode】树(共94题)的相关文章

【sql】leetcode习题 (共 42 题)

p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px Helvetica } [175]Combine Two Tables [176]Second Highest Salary [177]Nth Highest Salary [178]Rank Scores [180]Consecutive Numbers [181]Employees Earning More Than Their Managers [182]Duplicate Email

LeetCode面试常见100题( TOP 100 Liked Questions)

LeetCode面试常见100题( TOP 100 Liked Questions) 置顶 2018年07月16日 11:25:22 lanyu_01 阅读数 9704更多 分类专栏: 面试编程题真题合集 常见算法问题 LeetCode试题 LeetCode常见试题 版权声明:本文为博主原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明. 本文链接:https://blog.csdn.net/lanyu_01/article/details/81062232 这篇文章

[luogu]月下“毛景树”:树 剖 好 题

原题 题意: 给一棵树 , 每一条边都有边权 , 支持四种操作 1. 将第k条边权值修改为k 2. 将节点u到v的边权都覆盖为k 3. 将节点u到v的边权都增加k 4. 询问区间边权最大值 显然树剖 边权转点权然后就是树剖裸题了 怎样边权转点权 对于一个点u , 她的父亲是 v 将 u->v 的边权放到 u 上做点权 然后树剖最后的时候这样操作一波 1 if(a == b) 2 return; 3 if(dep[a] > dep[b]) 4 std::swap(a, b); 5 SgCover

HDU 4578 Transformation --线段树,好题

题意: 给一个序列,初始全为0,然后有4种操作: 1. 给区间[L,R]所有值+c 2.给区间[L,R]所有值乘c 3.设置区间[L,R]所有值为c 4.查询[L,R]的p次方和(1<=p<=3) 解法: 线段树,维护三个标记,addmark,mulmark,setmark分别表示3种更新,然后p[1],p[2],p[3]分别表示该节点的1,2,3次方和.标记传递顺序setmark一定是第一个,因为setmark可以使mulmark,addmark都失效还原,mulmark和addmark的顺

poj-3481-Double Queue-splay树的水题

很水的splay树. 会简单的操作即可... #include<stdio.h> #include<string.h> #include<algorithm> #include<iostream> #include<vector> using namespace std; #define maxn 1100000 #define mem(a,b) memset(a,b,sizeof(a)) #define root10 ch[ch[root][1

Leetcode 树 Unique Binary Search Trees

本文为senlie原创,转载请保留此地址:http://blog.csdn.net/zhengsenlie Unique Binary Search Trees Total Accepted: 13478 Total Submissions: 37858 Given n, how many structurally unique BST's (binary search trees) that store values 1...n? For example, Given n = 3, there

hdu 1754:I Hate It(线段树,入门题,RMQ问题)

I Hate It Time Limit: 9000/3000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 33726    Accepted Submission(s): 13266 Problem Description 很多学校流行一种比较的习惯.老师们很喜欢询问,从某某到某某当中,分数最高的是多少.这让很多学生很反感.不管你喜不喜欢,现在需要你做的是,就是按照老师的要求

hdu 1247:Hat’s Words(字典树,经典题)

Hat's Words Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 7282    Accepted Submission(s): 2639 Problem Description A hat's word is a word in the dictionary that is the concatenation of exactly

poj 2503:Babelfish(字典树,经典题,字典翻译)

Babelfish Time Limit: 3000MS   Memory Limit: 65536K Total Submissions: 30816   Accepted: 13283 Description You have just moved from Waterloo to a big city. The people here speak an incomprehensible dialect of a foreign language. Fortunately, you have