二叉树
一、平衡二叉树
后序遍历,计算左右子树的高度,设置flag变量,如果高度差大于1,则flag = 1,为false
/**
* 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:
//后序遍历,判断左右子树的高度差
//定义一个变量flag,如果高度差大于1令其等于1
int flag = 0;
int traversal(TreeNode* root) {
if (root == nullptr) return 0;
int leftDepth = traversal(root->left);
int rightDepth = traversal(root->right);
int result;
if (leftDepth - rightDepth > 1 || rightDepth - leftDepth > 1){
flag = 1;
}
else result = 1 + max(rightDepth, leftDepth);
return result;
}
bool isBalanced(TreeNode* root) {
//左右子树高度差不超过1
if (root == nullptr) return true;
traversal(root);
if (flag == 1) return false;
else return true;
}
};
二、二叉树的所有路径
1.递归前序遍历,记录遍历节点,遍历到叶子节点后,回溯到父节点,继续遍历右节点
2.迭代前序遍历,相对递归要简单一些,思路相同,记录遍历路径,当遍历到叶子节点,输出
/**
* 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:
vector<string> binaryTreePaths(TreeNode* root) {
//返回从根节点到叶子结点的路径
//迭代前序遍历,如果是叶子节点则加入
vector<string>result;
stack<string>path;
stack<TreeNode*>st;
if (root == nullptr) return result;
st.push(root);
path.push(to_string(root->val));
while (!st.empty()) {
TreeNode* node = st.top(); st.pop();
string treePath = path.top(); path.pop();
if (node->right == nullptr && node->left == nullptr) {
result.push_back(treePath);
}
if (node->right) {
st.push(node->right);
path.push(treePath + "->" + to_string(node->right->val));
}
if (node->left) {
st.push(node->left);
path.push(treePath + "->" + to_string(node->left->val));
}
}
return result;
}
};
三、左叶子之和
1.递归后序遍历,无法通过叶子节点判断是否为左叶子,通过父节点判断
2.迭代前序遍历,还是通过父节点判断是否为左叶子
/**
* 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 sumOfLeftLeaves(TreeNode* root) {
//返回所有左叶子之和
stack<TreeNode*>st;
if (root == nullptr) return 0;
st.push(root);
int sum = 0;
while (!st.empty()) {
TreeNode* node = st.top();
st.pop();
if (node->left &&node->left->right == nullptr && node->left->left == nullptr) {
sum += node->left->val;
}
if (node->right) st.push(node->right);
if (node->left) st.push(node->left);
}
return sum;
}
};
总结
左叶子之和和二叉树所有路径只有大概思路,写不出具体代码,继续加油!
学习时间90min。
学习资料:《代码随想录》。