/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<>();
if(root==null) return list;
Stack<TreeNode> rights = new Stack<>();
TreeNode node = root;
while(node != null){
list.add(node.val);
if(node.right != null){
rights.push(node.right);
}
node = node.left;
if(node == null && !rights.isEmpty()){
node = rights.pop();
}
}
return list;
}
}
[LeetCode] 144. Binary Tree Preorder Traversal
最新推荐文章于 2024-05-30 07:40:02 发布