二叉树的前序遍历

来源:互联网 发布:数据库软件工程师考试 编辑:程序博客网 时间:2024/05/22 14:49

1.问题描述

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

样例

给出一棵二叉树 {1,#,2,3},

   1    \     2    /   3

 返回 [1,2,3].

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
        vector<int>r;
        preorder(r,root);
        return r;
    }
        void preorder(vector<int>& r,TreeNode*root)
        {
        if(root==NULL)
        return;
         r.push_back(root->val);
            preorder(r,root->left);
            preorder(r,root->right);
        }
};

4.感想

代码中的vector相当于一个全局变量,在整个函数中只定义一次,目的就是所有节点都保存在一个vector 中。

0 0
原创粉丝点击