首页 > 代码库 > Leetcode 树 Binary Tree Preorder Traversal

Leetcode 树 Binary Tree Preorder Traversal

本文为senlie原创,转载请保留此地址:http://blog.csdn.net/zhengsenlie


Binary Tree Preorder Traversal

 Total Accepted: 17948 Total Submissions: 51578

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?


题意:先序遍历

思路:采用递归实现。因为函数声明是返回一个vector<int>,所以每个子树返回的是该子树的先序遍历的结果

按照 根、左、右的次序把根和左右子树的vector合并起来就可以了

复杂度:时间O(n),空间O(n)

相关题目:

Binary Tree Inorder Traversal

Binary Tree Postorder Traversal

/**
 * Definition for binary tree
 * 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> pre;
    	if(root == NULL) return pre;
    	TreeNode *left = root->left;
    	TreeNode *right = root->right;
    	pre.push_back(root->val);
    
    	if(left) {
    		vector<int> left_vector = preorderTraversal(left);
    		pre.insert(pre.end(), left_vector.begin(), left_vector.end());
    	}
    	if(right){
    		vector<int> right_vector = preorderTraversal(right);
    		pre.insert(pre.end(), right_vector.begin(), right_vector.end());
    	}
    	return pre;
    }
};