题目:
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?
二叉树的前序遍历
先看递归的写法(C++):
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution
{
private:
vector<int> result;
public:
vector<int> preorderTraversal(TreeNode *root)
{
if (root)
{
result.push_back(root->val);
preorderTraversal(root->left);
preorderTraversal(root->right);
}
return result;
}
};
二叉树的中序遍历每次都是走树的左分支(left),直到左子树为空,然后开始从递归的最深处返回,访问右子树。所以得有一个结构存储左子树访问结束后回溯的那个节点从而进行右子书的访问。这个结构就是栈Stack。
/**
* 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)
{
stack<TreeNode*> nodes;
vector<int> result;
TreeNode *node = root;
while (node || !nodes.empty())
{
//一路向右
if (node)
{
result.push_back(node->val);//先序遍历访问根节点
nodes.push(node);//节点入栈
node = node->left;
}
//右子树为空,追溯回最后的节点
else
{
node = nodes.top();
nodes.pop();//将此节点出栈
node = node->right;//指向此节点的右节点,将该节点当成根节点循环
}
}
return result;
}
};
C#代码:
/**
* Definition for binary tree
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int x) { val = x; }
* }
*/
public class Solution
{
public IList<int> PreorderTraversal(TreeNode root)
{
IList<int> result = new List<int>();
Stack<TreeNode> nodes = new Stack<TreeNode>();
TreeNode node = root;
while (node != null || nodes.Count > 0)
{
if (node != null)
{
result.Add(node.val);
nodes.Push(node);
node = node.left;
}
else
{
node = nodes.Pop();
node = node.right;
}
}
return result;
}
}
时间: 2024-11-07 03:47:45