(二叉树 递归) leetcode 144. Binary Tree Preorder Traversal

Given a binary tree, return the preorder traversal of its nodes' values.

Example:

Input: [1,null,2,3]
   1
    \
     2
    /
   3

Output: [1,2,3]

Follow up: Recursive solution is trivial, could you do it iteratively?

-----------------------------------------------------------------------------------------------------------

二叉树的前序遍历(preorder traversal)。emmm,虽然题目要求用非递归,但是,我现在先用递归来写(简单)。emmmm,只要理解透递归的含义,解决这个问题是异常的简单。

C++代码:递归代码1:

/**
 * 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> vec;
        DFS(root,vec);
        return vec;
    }
    void DFS(TreeNode* root,vector<int>& vec){
        if(!root) return;
        vec.push_back(root->val);
        if(root->left) DFS(root->left,vec);
        if(root->right) DFS(root->right,vec);
    }
};

递归代码2:

/**
 * 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> vec;
    vector<int> preorderTraversal(TreeNode* root) {
        if(!root) return vec;
        vec.push_back(root->val);
        preorderTraversal(root->left);
        preorderTraversal(root->right);
        return vec;
    }
};

 

上一篇:不同的数且找出下标


下一篇:allegro 转换铜皮形态_动态铜皮转换成静态铜皮_静态铜皮设置成动态铜皮105