leetcode [144]Binary Tree Preorder Traversal
Given a binary tree, return the preorder traversal of its nodes' values.
Example:
SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。Input:[1,null,2,3]1 \ 2 / 3 Output:[1,2,3]
Follow up: Recursive solution is trivial, could you do it iteratively?
题目大意:
使用非递归的解法,得到二叉树的前序遍历。
解法:
使用栈来做
java:
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer>res=new ArrayList<Integer>();
Stack<TreeNode>rights=new Stack<>();
while(root!=null){
res.add(root.val);
if(root.right!=null) rights.add(root.right);
root=root.left;
if(root==null&&!rights.empty()) root=rights.pop();
}
return res;
}
}
更多精彩

