leetcode第144题
https://leetcode-cn.com/problems/binary-tree-preorder-traversal/
给定一个二叉树,返回它的 前序 遍历。
示例:
输入: [1,null,2,3]
1
2
/
3
输出: [1,2,3]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
方法一 递归算法
leetcode代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
List list=new ArrayList<>();
public List preorderTraversal(TreeNode root) {
if(root==null)return list;
list.add(root.val);
preorderTraversal(root.left);
preorderTraversal(root.right);
return list;
}
}
自己写的包含主函数的代码:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Main {
static List list=new ArrayList<>();
public static void main(String[] args){
TreeNode root=new TreeNode(1);
root.left=new TreeNode(3);
root.right=new TreeNode(5);
root.left.left=new TreeNode(2);
root.right.left=new TreeNode(4);
preorderTraversal(root);
System.out.println(Arrays.toString(list.toArray()));
}
public static List preorderTraversal(TreeNode root) {
if(root==null)return list;
list.add(root.val);
preorderTraversal(root.left);
preorderTraversal(root.right);
return list;
}
}
class TreeNode{
int val;
TreeNode(){}
TreeNode (int val){
this.val=val;
}
TreeNode left;
TreeNode right;
}
方法一 循环遍历(使用Stack)
leetcode代码
import java.util.Stack;
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
List list=new ArrayList<>();
public List preorderTraversal(TreeNode root) {
if(root==null)return list;
Stackstack=new Stack<>();
while(root!=null||!stack.isEmpty()){
while(root!=null){
list.add(root.val);
stack.push(root);
root=root.left;
}
if(!stack.isEmpty()){
root=stack.pop();
root=root.right;
}
}
return list;
}
}
自主写的包含main方法的代码:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Stack;
public class Main {
static List list=new ArrayList<>();
public static void main(String[] args){
TreeNode root=new TreeNode(1);
root.left=new TreeNode(3);
root.right=new TreeNode(5);
root.left.left=new TreeNode(2);
root.right.left=new TreeNode(4);
preorderTraversal(root);
System.out.println(Arrays.toString(list.toArray()));
}
public static List preorderTraversal(TreeNode root) {
if(root==null)return list;
Stack stack=new Stack<>();
while(root!=null||!stack.isEmpty()){
while(root!=null){
list.add(root.val);
stack.push(root);
root=root.left;
}
if(!stack.isEmpty()){
root=stack.pop();
root=root.right;
}
}
return list;
}
}
class TreeNode{
int val;
TreeNode(){}
TreeNode (int val){
this.val=val;
}
TreeNode left;
TreeNode right;
}