题目:
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?
题解:
C++版
/**
* 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) {
stack<TreeNode*> unvisited;
vector<int> preorder;
if(!root)
return preorder;
unvisited.push(root);
while(unvisited.size()) {
TreeNode* current = new TreeNode(0);
current = unvisited.top();
unvisited.pop();
preorder.push_back(current->val);
if(current->right)
unvisited.push(current->right);
if(current->left)
unvisited.push(current->left);
}
return preorder;
}
};Java版
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<Integer>();
if(root == null)
return result;
Stack<TreeNode> unvisited = new Stack<TreeNode>();
unvisited.push(root);
while(!unvisited.empty()) {
TreeNode current = unvisited.pop();
result.add(current.val);
if(current.right != null)
unvisited.push(current.right);
if(current.left != null)
unvisited.push(current.left);
}
return result;
}
}Python版
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param root, a tree node
# @return a list of integers
def preorderTraversal(self, root):
result = []
if root == None:
return result
unvisited = [root]
while len(unvisited) != 0:
current = unvisited.pop()
result.append(current.val)
if current.right != None:
unvisited.append(current.right)
if current.left != None:
unvisited.append(current.left)
return result
412


: Binary Tree Preorder Traversal&spm=1001.2101.3001.11974&articleId=39983877&d=1&t=3&u=9e2325d08ed94ebebb0f4b4e1a92a629)

被折叠的 条评论
为什么被折叠?



