二叉树的递归遍历
前序遍历:
递归三部曲:
1、确定参数和返回值:传入list来存放节点,返回值为void:
java
public void preorder(TreeNode root, List<Integer> result)
2、确定终止条件:
java
if(root == null){
return;
}
3、确定单层递归的逻辑:
java
result.add(root.val);
preorder(root.left, result);
preorder(root.right, result);
综合代码:
java
public List<Integer> preorderTraversal(TreeNode root){
List<Integer> result = new ArrayList<Integer>();
preorder(root, result);
return result;
}
public void preorder(TreeNode root, List<Integer> result){
if(root == null){
return;
}
result.add(root.val);
preorder(root.left, result);
preorder(root.right, result);
}
中序遍历:
java
// 中序遍历·递归·LC94_二叉树的中序遍历
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
inorder(root, res);
return res;
}
void inorder(TreeNode root, List<Integer> list) {
if (root == null) {
return;
}
inorder(root.left, list);
list.add(root.val); // 注意这一句
inorder
后序遍历:
java
// 中序遍历·递归·LC94_二叉树的中序遍历
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
inorder(root, res);
return res;
}
void inorder(TreeNode root, List<Integer> list) {
if (root == null) {
return;
}
inorder(root.left, list);
list.add(root.val); // 注意这一句
inorder
迭代法:
java
class Solution{
public List<Integer> preorderTraversal(TreeNode root){
List<Integer> result = new ArrayList<>();
if(root == null){
return result;
}
}
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while(!stack.isEmpty){
TreeNode node = stack.pop();
result.add(node.val);
if(node.right != null){
stack.push(node.right);
}
if(node.left != null){
stack.push(node.left);
}
}
return result;
}