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

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

【题目】

Given a binary tree, return the preordertraversal of its nodes' values.

Example:

Input: [1,null,2,3]
1
\
2
/
3 Output: [1,2,3]

【思路】

有参考,好机智,使用堆栈压入右子树,暂时存储。

左子树遍历完成后遍历右子树。

【代码】

/**
* 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) {
LinkedList<Integer> ans=new LinkedList<Integer>();
Stack<TreeNode> tmp=new Stack<TreeNode>();
while(root!=null){
ans.add(root.val);
if(root.right!=null){
tmp.push(root.right);
}
root=root.left;
if(root==null&&!tmp.isEmpty()){
root=
tmp.pop();
}

}
return ans;
}
}