首页 > 代码库 > LeetCode: Binary Tree Preorder Traversal [144]

LeetCode: Binary Tree Preorder Traversal [144]

【题目】

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?


【题意】

    非递归返回先序遍历结果


【思路】

        维护一个栈即可


【代码】

/**
 * 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) {
        vector<int> result;
        stack<TreeNode*> st;
        TreeNode*node=root;
        while(node){
            result.push_back(node->val);
            st.push(node);
            node=node->left;
        }
        while(!st.empty()){
            node=st.top()->right; st.pop();
            while(node){
                result.push_back(node->val);
                st.push(node);
                node=node->left;
            }
        }
        return result;
    }
};