Binary Tree Preorder Traversal 分类: Leetcode(树) 2015-03-24 17:04 28人阅读 评论(0) 收藏
</pre><p>Binary Tree Preorder Traversal </p>Given a binary tree, return the preorder traversal of its nodes' values.For example:Given binary tree {1,#,2,3}, 1 \ 2 / 3return [1,2,3].<p></p><p>递归版本</p><p></p><pre name="code" class="cpp">/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<int> preorderTraversal(TreeNode *root) { vector<int> vec; pre(root, vec); return vec; } void pre(TreeNode *root, vector<int> &vec) { if (!root) return ; else vec.push_back(root->val); if(root->left) { pre(root->left, vec); } if(root->right) { pre(root->right, vec); } } };
栈版本:
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<int> preorderTraversal(TreeNode *root) { vector<int> result; stack<const TreeNode*> s; const TreeNode *p; p = root; if (p) s.push(p); while(!s.empty()) { p = s.top(); s.pop(); result.push_back(p->val); if (p->right) s.push(p->right); if (p->left) s.push(p->left); } return result; } };
Mirror算法
这个算法得特别讲解一下,这个算法的精髓可以理解为利用叶子节点的后继节点作为一个标记节点。
伪代码:
MirrorPreOrder()
while 当前节点非空
if 当前节点没有左后代
访问当前节点
转向当前节点的右后代节点
else
找到左后代的最右节点
if 该最右节点没有线索化
访问当前节点
指向当前节点
转向当前节点左后代节点
else
消除线索化
转向当前节点右后代节点
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<int> preorderTraversal(TreeNode *root) { vector<int> result; TreeNode *cur, *prev; cur =root ; while (cur) { if(!cur->left) { result.push_back(cur->val); prev = cur; cur = cur->right; } else { TreeNode *node = cur->left; while (node->right && node->right != cur) node = node ->right; if (!node->right) { result.push_back(cur->val); node->right = cur; prev = cur; cur = cur->left; } else { node->right = NULL; cur = cur->right; } } } return result; } };
版权声明:本文为博主原创文章,未经博主允许不得转载。