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].
尤其需要注意的是在每次迭代的过程中,都需要对树是否是空来判断

迭代版本

/**
 * 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> res;

        stack<TreeNode *>   st;
        if(root != NULL){
            st.push(root);

            while(!st.empty()){
                root = st.top();
                st.pop();
                res.push_back(root->val);
                //判断左右子树是否为空,一定要判断
                if(root->right)    st.push(root->right);
                if(root->left)     st.push(root->left);
            }
        }
        return res;
    }
};

递归版本

/**
 * 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 {
    vector<int> res;
public:
    vector<int> preorderTraversal(TreeNode* root) {
        if(!root)  return res;

        res.push_back(root->val);
        preorderTraversal(root->left);
        preorderTraversal(root->right);

        return res;
    }
};

results matching ""

    No results matching ""