力扣算法题—144Binary 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?

Solution:

  很简单,使用栈,先存入右节点,再存入左节点,这样就是先弹出左节点了

  

 1 class Solution {
 2 public:
 3     vector<int> preorderTraversal(TreeNode* root) {
 4         if (root == nullptr)return {};
 5         vector<int>res;
 6         stack<TreeNode*>s;
 7         s.push(root);
 8         while (!s.empty())
 9         {
10             TreeNode* p = s.top();
11             s.pop();
12             res.push_back(p->val);
13             if (p->right)s.push(p->right);
14             if (p->left)s.push(p->left);
15         }
16         return res;
17     }
18 };

猜你喜欢

转载自www.cnblogs.com/zzw1024/p/11774591.html
今日推荐