144. Binary Tree Preorder Traversal
Given a binary tree, return the preorder traversal of its nodes’ values.
Example:
Input: [1,null,2,3]
1
\
2
/
3
Output: [1,2,3]
Follow up: Recursive solution is trivial, could you do it iteratively?
二叉树先序遍历, 根节点-> 左子树-> 右子树。使用一个栈来维护已经访问过的节点。当节点不为空时,当前节点入栈,输出节点值,继续向左子树遍历。当root为空,从栈中弹出节点,向右子树进行遍历。
/**
* 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) {
if(root==NULL)
return vector<int>();
stack<TreeNode*> nodeStack;
vector<int> result;
while(!nodeStack.empty() || root != NULL)
{
while(root)
{
result.push_back(root->val);
nodeStack.push(root);
root=root->left;
}
TreeNode* node = nodeStack.top();
nodeStack.pop();
root = node->right;
}
return result;
}
};
还没有评论,来说两句吧...