lintcode 66 二叉树的前序遍历

来源:互联网 发布:iphone主题软件 编辑:程序博客网 时间:2024/05/18 00:41

1.给出一棵二叉树,返回其节点值的前序遍历。

2.用递归方法前序遍历二叉树,存在vector中,返回值

3.代码

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */


class Solution {
public:
    /**
     * @param root: The root of binary tree.
     * @return: Preorder in vector which contains node values.
     */
    vector<int> preorderTraversal(TreeNode *root) {
        // write your code here
       TreeNode *x = root;  
        vector<TreeNode*> p;  
        vector<int> res;  
        while(x != NULL || p.size() != 0){  
            res.push_back(x->val);  
            if (x->right != NULL)  
                p.push_back(x->right);  
            x = x->left;  
            if (x == NULL && p.size() != 0){  
                x = p.back();  
                p.pop_back();  
            }  
        }  
        return res;  
    }  
};  
        

4.感想

  在他们都在说递归递归的时候,说实话我是一脸懵逼的,啥叫递归?好心的王凯大哥细心地给我讲了递归之后,我才略微知道了这个大一学的知识点,仅仅是略微而已....先把第一个程序赶完,虽然一开始我不知道这个代码是什么意思.....

0 0