[leetcode] 144. Binary Tree Preorder Traversal 解题报告

题目链接:https://leetcode.com/problems/binary-tree-preorder-traversal/

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 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) return result;
        result.push_back(root->val);
        preorderTraversal(root->left);
        preorderTraversal(root->right);
        return result;
    }
private:
    vector<int> result;
};


迭代:

/**
 * 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) return result;
        stack<TreeNode*> st;
        st.push(root);
        while(!st.empty())
        {
            TreeNode *tem = st.top();
            st.pop();
            if(tem)
            {
                result.push_back(tem->val);
                st.push(tem->right);//注意左右子树入栈顺序
                st.push(tem->left);
            }
        }
        
        return result;
    }
private:
    vector<int> result;
};






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