\二叉树代码、建树
void BTree::buildTree(vector<int>&a)//创建
{
if (a.size() == 0)
{
return;
}
root = new TreeNode(a[0]);
for (int i = 1; i < a.size(); i++)
{
TreeNode *newNode = new TreeNode(a[i]);
TreeNode *node = root;
while (node)
{
if (a[i] < node->val)
{
if (node->left == NULL)
{
node->left = newNode;
break;
}
node = node->left;
}
else
{
if (node->right == NULL)
{
node->right = newNode;
break;
}
node = node->right;
}
}
}
}
\递归 先序、中序、后序遍历
void BTree::preOrder(TreeNode *root)//先序、根左右
{
if (root == NULL)
{
return;
}
cout << root->val << " ";
preOrder(root->left);
preOrder(root->right);
}
void BTree::inOrder(TreeNode *root)//中序、左根右
{
if (root == NULL)
{
return;
}
inOrder(root->left);
cout << root->val << " ";
inOrder(root->right);
}
void BTree::postOrder(TreeNode *root)//后序、左右根
{
if (root == NULL)
{
return;
}
postOrder(root->left);
postOrder(root->right);
cout << root->val << " ";
}
\非递归 先序、中序、后序
void BTree::preOrderfor(TreeNode* root)//先序
{
if (root == NULL)
{
return;
}
stack<TreeNode*>stk;
stk.push(root);
while (!stk.empty())
{
TreeNode *cur = stk.top();
stk.pop();
cout << cur->val << " ";
if (cur->right)
{
stk.push(cur->right);
}
if (cur->left)
{
stk.push(cur->left);
}
}
}
void BTree::inOrderfor(TreeNode* root)//中序
{
if (root == NULL)
{
return;
}
stack<TreeNode*>stk;
TreeNode* cur = root;
while (!stk.empty() || cur != NULL)
{
while (cur != NULL)
{
stk.push(cur);
cur = cur->left;
}
TreeNode *node = stk.top();
stk.pop();
cout << node->val << " ";
cur = node->right;
}
}
void BTree::postOrderfor(TreeNode* root)//后序
{
if (root == NULL)
{
return;
}
stack<TreeNode*>stk1;
stack<TreeNode*>stk2;
stk1.push(root);
while (!stk1.empty())
{
TreeNode *cur = stk1.top();
stk1.pop();
stk2.push(cur);
if (cur->left)
{
stk1.push(cur->left);
}
if (cur->right)
{
stk1.push(cur->right);
}
}
while (!stk2.empty())
{
cout << stk2.top()->val << " ";
stk2.pop();
}
}
层次遍历
void BTree::layerOrder(TreeNode* root)//层次遍历
{
if (root == NULL)
{
return;
}
queue<TreeNode*>que;/
que.push(root);
TreeNode *last = root;
TreeNode *nlast =NULL;
while (!que.empty())
{
TreeNode *cur = que.front();
que.pop();
cout << cur->val << " ";
if (cur->left)
{
que.push(cur->left);
nlast = cur->left;
}
if (cur->right)
{
que.push(cur->right);
nlast = cur->right;
}
if (cur == last)
{
cout << endl;
last = nlast;
}
}
}