首页 > 代码库 > 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: 51578Given 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; } };
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。