[LeetCode]144. Binary Tree Preorder Traversal二叉树前序遍历

时间:2023-03-10 04:17:32
[LeetCode]144. Binary Tree Preorder Traversal二叉树前序遍历

关于二叉树的遍历请看:

http://www.cnblogs.com/stAr-1/p/7058262.html

/*
考察基本功的一道题,迭代实现二叉树前序遍历
*/
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
if (root==null)
return res;
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while (!stack.isEmpty())
{
TreeNode cur = stack.pop();
res.add(cur.val);
if (cur.right!=null)
stack.push(cur.right);
if (cur.left!=null)
stack.push(cur.left);
}
return res;
}