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;
}
}*/