144. Binary Tree Preorder Traversal

蔚落 2022-05-04 01:28 274阅读 0赞

Given a binary tree, return the preorder traversal of its nodes’ values.

Example:

  1. Input: [1,null,2,3]
  2. 1
  3. \
  4. 2
  5. /
  6. 3
  7. Output: [1,2,3]

Follow up: Recursive solution is trivial, could you do it iteratively?

二叉树先序遍历, 根节点-> 左子树-> 右子树。使用一个栈来维护已经访问过的节点。当节点不为空时,当前节点入栈,输出节点值,继续向左子树遍历。当root为空,从栈中弹出节点,向右子树进行遍历。

  1. /**
  2. * Definition for a binary tree node.
  3. * struct TreeNode {
  4. * int val;
  5. * TreeNode *left;
  6. * TreeNode *right;
  7. * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
  8. * };
  9. */
  10. class Solution {
  11. public:
  12. vector<int> preorderTraversal(TreeNode* root) {
  13. if(root==NULL)
  14. return vector<int>();
  15. stack<TreeNode*> nodeStack;
  16. vector<int> result;
  17. while(!nodeStack.empty() || root != NULL)
  18. {
  19. while(root)
  20. {
  21. result.push_back(root->val);
  22. nodeStack.push(root);
  23. root=root->left;
  24. }
  25. TreeNode* node = nodeStack.top();
  26. nodeStack.pop();
  27. root = node->right;
  28. }
  29. return result;
  30. }
  31. };

发表评论

表情:
评论列表 (有 0 条评论,274人围观)

还没有评论,来说两句吧...

相关阅读