首页 > 代码库 > 144.Binary Tree Preorder Traversal(非递归前序遍历)
144.Binary Tree Preorder Traversal(非递归前序遍历)
Given a binary tree, return the preorder traversal of itsnodes‘ values.
For example:
Given binary tree {1,#,2,3},
1
\
2
/
3
return [1,2,3].
Note: Recursive solution istrivial, could you do it iteratively?
HideTags
Tree Stack
#pragma once #include<iostream> #include<vector> #include<stack> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; vector<int> preorderTraversal(TreeNode *root) { vector<int> result; stack<TreeNode*> s; TreeNode* p = root; while (p) { result.push_back(p->val); if (p->left)//有左,向左,右压栈 { if (p->right) s.push(p->right); p = p->left; } else if (p->right)//无左,有右,向右 p = p->right; else if (!s.empty())//无左无右,栈不空,pop { p = s.top(); s.pop(); } else return result;//无左无右栈空,返回 } return result;//不可少,若root==NULL,用这一句返回 } void main() { TreeNode* t1 = new TreeNode(1); TreeNode* t2 = new TreeNode(2); TreeNode* t3 = new TreeNode(3); TreeNode* t4 = new TreeNode(4); TreeNode* t5 = new TreeNode(5); TreeNode* t6 = new TreeNode(6); TreeNode* t7 = new TreeNode(7); TreeNode* t8 = new TreeNode(8); TreeNode* t9 = new TreeNode(9); TreeNode* t0 = new TreeNode(0); TreeNode* t10 = NULL; t1->right = t2; t2->left = t3; t4->left = t5; t4->right = t6; t7->right = t8; t8->right = t9; t1->left = t7; t7->left = t4; vector<int>result = preorderTraversal(t1); for (int i = 0; i < (int)result.size(); i++) cout << result[i] << " "; cout << endl; system("pause"); }
144.Binary Tree Preorder Traversal(非递归前序遍历)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。