一:解题思路
这道题目2种做法。第一种做法就是递归法,第二种就是迭代法。这2种方法的时间复杂度和空间复杂度都为O(n)。
二:完整代码示例 (C++版和Java版)
递归C++:
class Solution { public: void preorder(TreeNode* root, vector<int>& ret) { if (root != NULL) { ret.push_back(root->val); preorder(root->left,ret); preorder(root->right,ret); } } vector<int> preorderTraversal(TreeNode* root) { vector<int> ret; preorder(root,ret); return ret; } };
递归Java:
class Solution { public void preorder(TreeNode root,List<Integer> ret) { if(root!=null) { ret.add(root.val); preorder(root.left,ret); preorder(root.right,ret); } } public List<Integer> preorderTraversal(TreeNode root) { List<Integer> ret=new ArrayList<>(); preorder(root,ret); return ret; } }
迭代C++:
class Solution { public: vector<int> preorderTraversal(TreeNode* root) { vector<int> result; stack<TreeNode*> stack; while (root != NULL || !stack.empty()) { while (root != NULL) { result.push_back(root->val); stack.push(root); root = root->left; } root=stack.top()->right; stack.pop(); } return result; } };
迭代Java:
class Solution { public List<Integer> preorderTraversal(TreeNode root) { List<Integer> ret=new ArrayList<>(); Stack<TreeNode> stack=new Stack<>(); while(root!=null || !stack.isEmpty()) { while(root!=null) { ret.add(root.val); stack.push(root); root=root.left; } root=stack.pop().right; } return ret; } }