144.二叉树前序遍历
原题链接: 二叉树前序遍历
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<Integer> list;
public List<Integer> preorderTraversal(TreeNode root) {
list = new ArrayList<>();
search(root);
return list;
}
public void search(TreeNode root){
if(root==null)
return;
list.add(root.val);
search(root.left);
search(root.right);
}
}
145.二叉树后序遍历
原题链接: 二叉树后序遍历
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<Integer> list;
public List<Integer> postorderTraversal(TreeNode root) {
list = new ArrayList<>();
search(root);
return list;
}
public void search(TreeNode root){
if(root==null)
return;
search(root.left);
search(root.right);
list.add(root.val);
}
}
94.二叉树中序遍历
原题链接: 二叉树中序遍历
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<Integer> list;
public List<Integer> inorderTraversal(TreeNode root) {
list = new ArrayList<>();
search(root);
return list;
}
public void search(TreeNode root){
if(root==null)
return;
search(root.left);
list.add(root.val);
search(root.right);
}
}