-
非递归实现先序遍历
-
很简单的一道题目。用栈实现即可。根节点压入栈,然后判断栈是否为空。不为空,弹出top节点。判断top节点右左节点是否存在,存在则压入栈,直到栈为空。
-
#include
#include
using namespace std;
struct TreeNode
{
int val;
TreeNode lChild;
TreeNode rChild;
TreeNode(int val, TreeNodel = nullptr, TreeNoder = nullptr)
{
this->val = val;
this->lChild = l;
this->rChild = r;
}
};
TreeNode *create(int intarr[], int length, int i)
{
TreeNode *node = nullptr;if (i < length && intarr[i] != -1)
{
node = new TreeNode(intarr[i]);
node->lChild = create(intarr, length, i * 2 + 1);
node->rChild = create(intarr, length, i * 2 + 2);
}
return node;
}
void postOrder(TreeNode *node)
{
if (node)
{
cout << node->val << " ";
postOrder(node->lChild);
postOrder(node->rChild);
}
}
void postOrderByStack(TreeNode *node)
{
stack<TreeNode *> nodeStack;
nodeStack.push(node);
while (!nodeStack.empty())
{
TreeNode *temp = nodeStack.top();
cout << temp->val << " ";
nodeStack.pop();
if (temp->rChild)
nodeStack.push(temp->rChild);
if (temp->lChild)
nodeStack.push(temp->lChild);
}
}
int main()
{
int arr[7] = { 3,9,20,-1,-1,15,7 };
TreeNode *root = create(arr, 7, 0);
postOrder(root);
cout << endl;
postOrderByStack(root);
cout << endl;
system(“pause”);
return 0;
}
[LeetCode] Binary Tree Preorder Traversal 二叉树的先序遍历
最新推荐文章于 2020-01-17 21:25:47 发布