55. Binary Tree Preorder Traversal

  1. Binary Tree Preorder Traversal My Submissions QuestionEditorial Solution
    Total Accepted: 119655 Total Submissions: 300079 Difficulty: Medium
    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].

思路:用栈来进行先序遍历,先入栈的后遍历
时间复杂度:O(n)
空间复杂度:O(1)

/** * 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) {
        vector<int> vtn;
        if(root==NULL)return vtn;  //为空时先处理,不然后面死循环
        stack<TreeNode*> stn;
        stn.push(root);
        while(!stn.empty()){
            TreeNode *p = stn.top();
            vtn.push_back(p->val);
            stn.pop();
            if(p->right!=NULL)stn.push(p->right);
            if(p->left!=NULL)stn.push(p->left);
        }
        return vtn;
    }
};

你可能感兴趣的:(tree,binary,traversal,preorder)