Binary Tree Preorder Traversal
Medium
Given a binary tree, return the preorder traversal of its nodes’ values.
Example:
Input: [1,null,2,3]
1
\
2
/
3
Output: [1,2,3]
Follow up: Recursive solution is trivial, could you do it iteratively?
题意
二叉树的先序遍历,要求用循环不能用递归
思路
递归的栈模拟,相应的递归解法请移步:144. Binary Tree Preorder Traversal
代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> ans = new ArrayList<Integer>();
LinkedList<TreeNode> stack = new LinkedList<TreeNode>();
if (root == null) {
return ans;
}
stack.add(root);
while (!stack.isEmpty()) {
root = stack.removeLast();
ans.add(root.val);
if (root.right != null) {
stack.add(root.right);
}
if (root.left != null) {
stack.add(root.left);
}
}
return ans;
}
}