Given a binary tree, return the preorder traversal of its nodes' values.
使用非递归的方法:递归的方法见
http://blog.csdn.net/doc_sgl/article/details/14436785
/**
* 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<TreeNode* > stk;
while(root!=NULL || !stk.empty())
{
if(root != NULL)
{
result.push_back(root->val);
stk.push(root);
root = root ->left;
}
else
{
root = stk.top();
root = root->right;
stk.pop();
}
}
return result;
}
};
Python version:
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param root, a tree node
# @return a list of integers
def preorderTraversal(self, root):
result = []
stack = []
while root or stack:
if root:
result.append(root.val)
stack.append(root)
root = root.left
else:
root = stack.pop()
root = root.right
return result
Given a binary tree, return the inorder traversal of its nodes' values.
使用递归的方法,非递归的方法没有实现
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
void inorder(TreeNode *root,vector<int>& path)
{
if(root !=NULL)
{
inorder(root->left,path);
path.push_back(root->val);
inorder(root->right,path);
}
}
vector<int> inorderTraversal(TreeNode *root) {
vector<int> result;
inorder(root,result);
return result;
}
};