博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LintCode] 二叉树的前序遍历
阅读量:5825 次
发布时间:2019-06-18

本文共 2692 字,大约阅读时间需要 8 分钟。

The recursive solution is trivial and I omit it here.

Iterative Solution using Stack (O(n) time and O(n) space):

1 /** 2  * Definition of TreeNode: 3  * class TreeNode { 4  * public: 5  *     int val; 6  *     TreeNode *left, *right; 7  *     TreeNode(int val) { 8  *         this->val = val; 9  *         this->left = this->right = NULL;10  *     }11  * }12  */13 14 class Solution {15 public:16     /**17      * @param root: The root of binary tree.18      * @return: Preorder in vector which contains node values.19      */20     vector
preorderTraversal(TreeNode *root) {21 // write your code here22 vector
nodes;23 TreeNode* node = root;24 stack
right;25 while (node || !right.empty()) {26 if (node) {27 nodes.push_back(node -> val);28 if (node -> right)29 right.push(node -> right);30 node = node -> left;31 }32 else {33 node = right.top();34 right.pop();35 }36 }37 return nodes;38 }39 };

Another more sophisticated solution using Morris Traversal (O(n) time and O(1) space):

1 /** 2  * Definition of TreeNode: 3  * class TreeNode { 4  * public: 5  *     int val; 6  *     TreeNode *left, *right; 7  *     TreeNode(int val) { 8  *         this->val = val; 9  *         this->left = this->right = NULL;10  *     }11  * }12  */13 14 class Solution {15 public:16     /**17      * @param root: The root of binary tree.18      * @return: Preorder in vector which contains node values.19      */20     vector
preorderTraversal(TreeNode *root) {21 // write your code here22 vector
nodes;23 TreeNode* node = root;24 while (node) {25 if (node -> left) {26 TreeNode* predecessor = node -> left;27 while (predecessor -> right && predecessor -> right != node)28 predecessor = predecessor -> right;29 if (!(predecessor -> right)) {30 nodes.push_back(node -> val);31 predecessor -> right = node;32 node = node -> left;33 }34 else {35 predecessor -> right = NULL;36 node = node -> right;37 }38 }39 else {40 nodes.push_back(node -> val);41 node = node -> right;42 }43 }44 return nodes;45 }46 };

 

转载于:https://www.cnblogs.com/jcliBlogger/p/4607615.html

你可能感兴趣的文章
CSS3
查看>>
ul下的li浮动,如何是ul有li的高度
查看>>
C++ primer plus
查看>>
python mysqlDB
查看>>
UVALive 3942 Remember the Word Tire+DP
查看>>
Android之HttpClient
查看>>
从微软的DBML文件中我们能学到什么(它告诉了我们什么是微软的重中之重)~目录...
查看>>
被需求搞的一塌糊涂,怎么办?
查看>>
c_数据结构_队的实现
查看>>
jquery 选择器总结
查看>>
1月10日,11日工作情况
查看>>
Qt设置背景图片
查看>>
Grunt使用心得
查看>>
【阿里云文档】常用文档整理
查看>>
iptables 配置需要保存
查看>>
.NET各种小问题
查看>>
ApkTool反编译和重新打包
查看>>
OpenState: Programming Platform-independent Stateful OpenFlow Applications Inside the Switch
查看>>
java中的Volatile关键字
查看>>
前端自定义图标
查看>>