一棵binary tree由node的有限集合组成。
这个集合为empty或者由一个root以及两棵不相交的二叉树组成,分别叫
left subtree和right subtree,又称为root结点的children,root和subtree通过edge(边)相连,children对应的是parent。
路径:path
长度:length
祖先:ancestor
子孙:descendant
所有结点都是根结点的descendant,根结点是它们的ancestor。
根结点的深度为0,层数为0,高度为1。
======================
满二叉树:full binary tree
完全二叉树:complete binary tree
满二叉树定理①:非空满二叉树的叶结点数等于其分支结点数加1.
周游\遍历(traversal)二叉树:
对下图作遍历:
前序遍历:一般用作遍历访问每个结点。
A B D C E G F H I
中序遍历:如二叉搜索树。
B D A G E C H F I
后序遍历:如需要遍历删除结点时,先删除子节点。
D B G E H I F C A
- 结点里不需要添加指向父节点的指针。
==========================================
题目:
给定一棵二叉树,返回其节点值的前序遍历。
例如:
给定二叉树[1,null,2,3],
1
\
2
/
3
返回 [1,2,3]。
解:
//构造一棵二叉树。
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
//方法一,效率一般,不好理解
vector<int> preorderTraversal(TreeNode* root) {
vector<int>result;
TreeNode*p = root;
vector<TreeNode*>vecNode;
while (p != NULL || vecNode.size() != 0) {
result.push_back(p->val);
if (p->right != NULL)
vecNode.push_back(p->right);
p = p->left;
if (p == NULL&&vecNode.size() != 0) {
p = vecNode.back();
vecNode.pop_back();
}
}
return result;
}
};
//方法二,使用stack,较快:
#include<stack>
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> result;
if (root==nullptr) return result;
stack<TreeNode*> S;
S.push(root);
while (!S.empty()){
TreeNode* p=S.top();
S.pop();
result.push_back(p->val);
if (p->right) S.push(p->right);
if (p->left) S.push(p->left);
}
return result;
}
};
求中序遍历:
//stack
vector<int> inorderTraversal(TreeNode* root) {
vector<int>result;
stack<TreeNode*>S;
while (root != NULL || !S.empty()) {
if (root != NULL) {
S.push(root);
root = root->left;
}
else {
root = S.top();
S.pop();
result.push_back(root->val);
root = root->right;
}
}
return result;
}
//递归
vector<int> digui(TreeNode*root) {
vector<int> result;
inOrder(root, result);
return result;
}
void inOrder(TreeNode*root, vector<int>&res) {
if (!root) return;
if (root->left) inOrder(root->left, res);
res.push_back(root->val);
if (root->right) inOrder(root->right, res);
}
求后序遍历:
vector<int> postorderTraversal(TreeNode* root) {
vector<int>result;
stack<TreeNode*>S;
if (root == NULL)return result;
TreeNode*cur;
TreeNode*pre = NULL;
S.push(root);
while (!S.empty())
{
cur = S.top();
if ((cur->left == NULL&&cur->right == NULL) || ((pre != NULL) && (pre == cur->left || pre == cur->right))) {
result.push_back(cur->val);
S.pop();
pre = cur;
}
else {
if (cur->right)S.push(cur->right);
if (cur->left)S.push(cur->left);
}
}
return result;
}