public ArrayList<Integer> preorderTraversal(TreeNode root) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
ArrayList<Integer> result = new ArrayList<Integer>();
if(root == null) return result;
Stack<TreeNode> stack = new Stack<TreeNode>();
stack.push(root);
while(!stack.isEmpty()) {
TreeNode tmp = stack.pop();
result.add(tmp.val);
if(tmp.right != null) stack.push(tmp.right);
if(tmp.left != null) stack.push(tmp.left);
}
return result;
}
Binary Tree Preorder Traversal
最新推荐文章于 2024-05-30 07:40:02 发布