二叉树的理论基础
二叉树递归遍历(前序中序后序)
① 递归法
class Solution {
List<Integer> list = new ArrayList<>();
public List<Integer> preorderTraversal(TreeNode root) {
dfs(root);
return list;
}
public void dfs(TreeNode root){
if(root == null)
return ;
list.add(root.val);
dfs(root.left);
dfs(root.right);
}
}
② 迭代法
lass Solution {
List<Integer> list = new ArrayList<>();
public List<Integer> preorderTraversal(TreeNode root) {
if(root == null)
return list;
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
TreeNode node;
while(!stack.isEmpty()){
node = stack.pop();
list.add(node.val);
if(node.right!=null)
stack.push(node.right);
if(node.left!=null)
stack.push(node.left);
}
return list;
}
}
① 递归法
class Solution {
List<Integer> list = new ArrayList<>();
public List<Integer> inorderTraversal(TreeNode root) {
dfs(root);
return list;
}
public void dfs(TreeNode root){
if(root == null)
return ;
dfs(root.left);
list.add(root.val);
dfs(root.right);
}
}
① 递归法
class Solution {
List<Integer> list = new ArrayList<>();
public List<Integer> postorderTraversal(TreeNode root) {
dfs(root);
return list;
}
public void dfs(TreeNode root){
if(root == null)
return ;
dfs(root.left);
dfs(root.right);
list.add(root.val);
}
}