[Leetcode] 144. 二叉树的前序遍历 java

给定一个二叉树，返回它的 前序 遍历。

示例:

输入: [1,null,2,3]
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) {
List<Integer> list=new ArrayList<>();
if(root==null) return list;
recursion(root,list);
return list;
}
public void recursion(TreeNode root,List<Integer> list){
if(root==null) return;
else{
recursion(root.left,list);
recursion(root.right,list);
}
}
}

/**
* 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) {
List<Integer> list=new ArrayList<>();
Stack<TreeNode> stack=new Stack<>();
if(root==null) return list;
stack.push(root);
while(!stack.isEmpty()){
TreeNode curr=stack.pop();
if(curr.right!=null) stack.push(curr.right);
if(curr.left!=null) stack.push(curr.left);
}
return list;
}
}

07-21 2521

09-16 60
02-08 1952
08-12 2591
03-02 253
10-24 1275
05-11 2516
07-13 733
01-19 9359
08-18 5614
07-23 2605
10-05 5798
05-01 1070
05-23 1749
08-31 207
11-27 519