二叉树主要有两种形式:满二叉树和完全二叉树
如果一颗二叉树只有度为0的结点和度为2的结点,且度为0的结点在同一层。
在完全二叉树中,除了最底层节点可能没填满外,其余每层节点数都达到最大值,并且最下面一层的节点都集中在该层最左边的若干位置。
/**
* 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* root, vector& vec) {
if (root == nullptr) return;
vec.push_back(root->val);
traversal(root->left, vec);
traversal(root->right, vec);
}
vector preorderTraversal(TreeNode* root) {
vector result;
traversal(root, result);
return result;
}
};
/**
* 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 *root, vector& vec) {
if (root == nullptr) return;
traversal(root->left, vec);
traversal(root->right, vec);
vec.push_back(root->val);
}
vector postorderTraversal(TreeNode* root) {
vector result;
traversal(root, result);
return result;
}
};
/**
* 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* root, vector& vec) {
if (root == nullptr) return;
traversal(root->left, vec);
vec.push_back(root->val);
traversal(root->right, vec);
}
vector inorderTraversal(TreeNode* root) {
vector result;
traversal(root, result);
return result;
}
};
前序遍历
class Solution {
public:
vector preorderTraversal(TreeNode* root) {
vector result;
stack st;
if (root == nullptr) return result;
st.push(root);
while (!st.empty()) {
TreeNode* node = st.top();
st.pop();
result.push_back(node->val);
if (node->right) st.push(node->right);
if (node->left) st.push(node->left);
}
return result;
}
};
后序遍历
class Solution {
public:
vector postorderTraversal(TreeNode* root) {
vector result;
stack st;
if (root == nullptr) return result;
st.push(root);
while (!st.empty()) {
TreeNode* node = st.top();
st.pop();
result.push_back(node->val);
if (node->left) st.push(node->left);
if (node->right) st.push(node->right);
}
reverse(result.begin(), result.end());
return result;
}
};
中序遍历
class Solution {
public:
vector inorderTraversal(TreeNode* root) {
vector result;
stack st;
TreeNode* cur = root;
while (cur != nullptr || !st.empty()) {
if (cur != nullptr) {
st.push(cur);
cur = cur->left;
} else {
cur = st.top();
st.pop();
result.push_back(cur->val);
cur = cur->right;
}
}
return result;
}
};