平衡二叉树
[题目](110. 平衡二叉树)
重点
要使用后序遍历
代码实现
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int getHeight(TreeNode* node) {
if (node == NULL) {
return 0;
}
// 左
int leftHeight = getHeight(node->left);
if (leftHeight == -1) {
return -1;
}
// 右
int rightHeight = getHeight(node->right);
if (rightHeight == -1) {
return -1;
}
// 中
return abs(leftHeight - rightHeight) > 1 ? -1 : 1 + max(leftHeight, rightHeight);
}
bool isBalanced(TreeNode* root) {
return getHeight(root) == -1 ? false : true;
}
};
二叉树的所有路径
[题目](257. 二叉树的所有路径)
重点
使用前序遍历,因为只有前序遍历是父节点指向子节点
要用到回溯
代码实现
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
void traversal(TreeNode* cur, vector<int> & path, vector<string> & result) {
// 中,因为最后一个节点也要加入到path中
path.push_back(cur->val);
// 这才到了叶子节点
if (cur->left == NULL && cur->right == NULL) {
string sPath;
for (int i = 0; i < path.size() - 1; i++) {
sPath += to_string(path[i]);
sPath += "->";
}
sPath += to_string(path[path.size() - 1]);
result.push_back(sPath);
return;
}
// 左
if (cur->left) {
traversal(cur->left, path, result);
// 回溯
path.pop_back();
}
// 右
if (cur->right) {
traversal(cur->right, path, result);
// 回溯
path.pop_back();
}
}
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> result;
vector<int> path;
if (root == NULL) {
return result;
}
traversal(root, path, result);
return result;
}
};