• 周四. 10 月 3rd, 2024

5G编程聚合网

5G时代下一个聚合的编程学习网

热门标签

Leetcode 144: preorder traversal of binary tree (Java)

King Wang

1 月 3, 2022

LeetCode 144: Preorder traversal of two tree (java)

subject :

answer :

/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
List<Integer> res=new ArrayList<>();
public List<Integer> preorderTraversal(TreeNode root) {
if(root!=null){
res.add(root.val);
preorderTraversal(root.left);
preorderTraversal(root.right);
}
return res;
}
}
/*
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> res=new ArrayList<>();
Stack<TreeNode> nodeStack=new Stack<>();
TreeNode nodeTemp=root;
while(nodeTemp!=null || !nodeStack.isEmpty()){
if(nodeTemp!=null){
nodeStack.push(nodeTemp);
res.add(nodeTemp.val);
nodeTemp=nodeTemp.left;
}else{
nodeTemp=nodeStack.pop();
nodeTemp=nodeTemp.right;
}
}
return res;
}
}*/

 

发表回复