标签:
Given a binary tree, return the preorder traversal of its nodes‘ values.
For example:
Given binary tree {1,#,2,3}
,
1 2 / 3
return [1,2,3]
.
Note: Recursive solution is trivial, could you do it iteratively?
本题为二叉树的先序遍历,也就是先根遍历,但是提示不能用递归,所以就是二叉树先序遍历的非递归实现。现在为了在面试中能够灵活的掌握非递归遍历,三种遍历方法都总结一下,方面以后的面试中复习使用。
先序遍历:
递归:
void traverse(Tree *root) { if(root==NULL) return; visit(root->data); traverse(Tree->left); traverse(Tree->right); }非递归(用栈实现,是因为递归的过程就是程序自动压栈);
void traverse(Tree *root) { stack.push(root); while(!stack.empty()) { temp=stack.top(); stack.pop(); visit(temp->data); stack.push(temp->right);//先将右儿子入栈,因为比左儿子更晚访问到 stack.push(temp->left); } }中序遍历:
递归:
void traverse(Tree *root){ if(root==NULL) return; traverse(Tree->left); visit(root->data); traverse(Tree->right); }后序遍历:
递归:
void traverse(Tree *root){ if(root==NULL) return; traverse(Tree->left); traverse(Tree->right); visit(root->data); }
/** * Definition for a binary tree node. * 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) { TreeNode* temp; stack<TreeNode *> st; st.push(root); while(!st.empty()) { temp=st.top(); st.pop(); visit(temp->val); st.push(temp->right); st.push(temp->left); } } };
版权声明:本文为博主原创文章,未经博主允许不得转载。
leetcode: Binary Tree Preorder Traversal
标签:
原文地址:http://blog.csdn.net/flyljg/article/details/47426837