一个二叉树的节点定义为:
struct TreeNode
{
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int v): val(v), left(nullptr), right(nullptr){}
};
1. 二叉树简单算法
- 将新节点newNode插入节点parent下方作为其左子
void insertNode(TreeNode* parent, TreeNode* newNode)
{
TreeNode* origLeft = parent->left; //parent原左子
TreeNode* origRight = parent->right; //parent原右子
parent->left = newNode;
newNode->left = origLeft;
newNode->right = origRight;
}
- 求二叉树最大深度
int maxDepth(TreeNode* root)
{
if (!root) return 0;
return 1 + max(maxDepth(root->left), maxDepth(root->right));
}
- 求二叉树最小深度
int minDepth(TreeNode* root)
{
if (!root) return 0;
if (!root->left) return 1+minDepth(root->right);
if (!root->right) return 1+minDepth(root->left);
return 1+min(minDepth(root->left), minDepth(root->right));
}
- 判断二叉树是否平衡
bool isBalanced(TreeNode* root)
{
return (manDepth(root) - minDepth(root) <= 1);
}
2. 二叉树遍历
- 层次遍历(level order traversal)
vector<int> levelOrderTrv(TreeNode* root)
{
vector<int> res;
queue<TreeNode*> qu;
qu.push(root);
while (!qu.empty())
{
TreeNode* curr = qu.front()
res.push_back(curr->val);
if (!curr->left) qu.push(curr->left);
if (!curr->right) qu.push(curr->right);
qu.pop();
}
return res;
}
- 前序遍历(pre-order traversal)
递归法:
vector<int> preOrderTrv(TreeNode* root)
{
vector<int> res;
preOrder(root, res);
return res;
}
void preOrder(TreeNode* root, vector<int> res)
{
if (!root) return;
res.push_back(root->val);
preOrder(root->left);
preOrder(root->right);
}
迭代法:
vector<int> preOrderTrv(TreeNode* root)
{
vector<int> res;
stack<TreeNode*> st;
TreeNode* curr = root;
st.push(curr);
while (!st.empty())
{
curr = st.top();
res.push_back(curr->val);
st.pop();
if (curr->right) st.push(curr->right);
if (curr->left) st.push(curr->left);
}
return res;
}
- 中序遍历(in-order traversal)
递归法:
vector<int> inOrderTrv(TreeNode* root)
{
vector<int> res;
inOrder(root, res);
return res;
}
void inOrder(TreeNode* root, vector<int> res)
{
if (!root) return;
res.push_back(root->val);
inOrder(root->left);
inOrder(root->right);
}
迭代法:
vector<int> inOrderTrv(TreeNode* root)
{
vector<int> res;
stack<TreeNode*> st;
TreeNode* curr = root;
while (!curr || !st.empty())
{
while (!curr)
{
st.push(curr);
curr = curr->left;
}
curr = st.top();
st.pop();
res.push_back(curr->val);
curr = curr->right;
}
return res;
}
- 后序遍历(post-order traversal)
递归法:
vector<int> postOrderTrv(TreeNode* root)
{
vector<int> res;
postOrder(root, res);
return res;
}
void postOrder(TreeNode* root, vector<int> res)
{
if (!root) return;
res.push_back(root->val);
postOrder(root->left);
postOrder(root->right);
}
迭代法:
vector<int> postOrderTrv(TreeNode* root)
{
vector<int> res;
stack<TreeNode*> s1;
stack<TreeNode*> s2;
s1.push(root);
while (!s1.empty())
{
TreeNode* curr = s1.top();
s1.top();
s2.push(curr);
if (curr->left) s1.push(curr->left);
if (curr->right) s1.push(curr->right);
}
while (!s2.empty())
{
TreeNode* node = s2.top();
res.push_back(node->val);
s2.pop();
}
return res;
}