144.二叉树的前序遍历
给你二叉树的根节点 root
,返回它节点值的 前序 遍历。
定义二叉树的节点类:
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;
}
}
代码实现(递归法)
递归法三要素:
1.确定递归函数的返回值
2.确定终止条件
3.确定递归的递进逻辑
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<>();
preorder(root,result);
return result;
}
private void preorder(TreeNode root,List<Integer> result){
if(root==null){
return;
}
result.add(root.val);
preorder(root.left,result);
preorder(root.right,result);
}
}
94.二叉树的中序遍历
将要处理的节点顺序放到中间即可
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<>();
inorder(root,result);
return result;
}
private void inorder(TreeNode root,List<Integer> result){
if(root==null){
return;
}
inorder(root.left,result);
result.add(root.val);
inorder(root.right,result);
}
}
145.二叉树的后序遍历
将要处理的节点顺序放到最后即可
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<>();
postorder(root,result);
return result;
}
private void postorder(TreeNode root,List<Integer> result){
if(root==null){
return;
}
postorder(root.left,result);
postorder(root.right,result);
result.add(root.val);
}
}