结果明天更新变成了明年更新。
去年快手和字节面试时都考了二叉树的前序遍历非递归实现,等我以后要是面试人我也要考这个哈哈。
递归的英文是recursive,非加non。
非递归中序竟然是凭着之前的模糊记忆写的。
具体讲解有缘更新。
#include <iostream>
#include <vector>
#include <stack>
using namespace std;
struct TreeNode
{
int val;
TreeNode* left, *right;
TreeNode(int _val):val(_val),left(nullptr),right(nullptr)
{}
};
void digui_preOrder(TreeNode* root)
{
if (!root)
return;
cout << root->val<<" ";
digui_preOrder(root->left);
digui_preOrder(root->right);
}
void digui_inOrder(TreeNode* root)
{
if (!root)
return;
digui_inOrder(root->left);
cout << root->val << " ";
digui_inOrder(root->right);
}
void disdigui_preOrder(TreeNode* root)
{
stack<TreeNode*> s;
while (root||!s.empty())
{
if (!root)
{
root = s.top();
s.pop();
}
cout << root->val;
if (root->right)
s.push(root->right);
root = root->left;
}
}
void disdigui_inOrder(TreeNode* root)
{
stack<TreeNode*> s;
while (root || !s.empty())
{
if (!root)
{
cout << s.top()->val << " ";
root = s.top()->right;
s.pop();
}
else
{
s.push(root);
/* if (root->right)
s.push(root->right);*/
root = root->left;
}
}
}
int main()
{
TreeNode* root = new TreeNode(0);
root->left = new TreeNode(1);
root->right = new TreeNode(2);
root->left->left = new TreeNode(3);
root->left->right = new TreeNode(4);
root->right->right = new TreeNode(5);
digui_preOrder(root);
cout << endl;
disdigui_preOrder(root);
cout << endl;
digui_inOrder(root);
cout << endl;
disdigui_inOrder(root);
}