Binary Tree Preorder Traversal
题目要求:
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?
递归解法
对这道题,用递归是最简单的了,具体程序如下:
/**
* 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) {
vector<int> rVec;
preorderTraversal(root, rVec);
return rVec;
} void preorderTraversal(TreeNode *tree, vector<int>& rVec)
{
if(!tree)
return; rVec.push_back(tree->val);
preorderTraversal(tree->left, rVec);
preorderTraversal(tree->right, rVec);
}
};
非递归解法
非递归解法相对就要难很多了,理解起来比较抽象。在这里我们需要借助栈。当左子树遍历完后,需要回溯并遍历右子树。具体程序如下:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> rVec;
stack<TreeNode *> st;
TreeNode *tree = root;
while(tree || !st.empty())
{
if(tree)
{
st.push(tree);
rVec.push_back(tree->val);
tree = tree->left;
}
else
{
tree = st.top();
st.pop();
tree = tree->right;
}
} return rVec;
}
更为简洁非递归解法
具体程序如下:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> rVec;
if(!root)
return rVec; stack<TreeNode *> st;
st.push(root);
while(!st.empty())
{
TreeNode *tree = st.top();
rVec.push_back(tree->val);
st.pop();
if(tree->right)
st.push(tree->right);
if(tree->left)
st.push(tree->left);
} return rVec;
}
Binary Tree Inorder Traversal
题目要求:
Given a binary tree, return the inorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3}
,
1
\
2
/
3
return [1,3,2]
.
Note: Recursive solution is trivial, could you do it iteratively?
这道题的非递归解法跟上题的非递归解法基本一致,只是访问的节点时机不一样。详细分析可参考LeetCode上的一篇博文。具体程序如下:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> rVec;
stack<TreeNode *> st;
TreeNode *tree = root;
while(tree || !st.empty())
{
if(tree)
{
st.push(tree);
tree = tree->left;
}
else
{
tree = st.top();
rVec.push_back(tree->val);
st.pop();
tree = tree->right;
}
} return rVec;
}
Binary Tree Postorder Traversal
题目要求:
Given a binary tree, return the postorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3}
,
1
\
2
/
3
return [3,2,1]
.
Note: Recursive solution is trivial, could you do it iteratively?
除了递归法,这道题利用两个栈来解决问题的话会比较方便,详细可参考LeetCode上的一篇文章。具体程序如下:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> rVec;
if(!root)
return rVec; stack<TreeNode *> st;
stack<TreeNode *> output;
st.push(root);
while(!st.empty())
{
TreeNode *tree = st.top();
output.push(tree);
st.pop();
if(tree->left)
st.push(tree->left);
if(tree->right)
st.push(tree->right);
} while(!output.empty())
{
rVec.push_back(output.top()->val);
output.pop();
} return rVec;
}