前序遍历:
访问根节点——访问左子树——访问右子树
中序遍历
访问左子树——访问根节点——访问右子树
后序遍历
访问左子树——访问右子树——访问根节点
实例演示:
对于如下的二叉树:
前序遍历:GDAFEMHZ
中序遍历:ADEFGHMZ
后序遍历:AEFDHZMG
前序遍历代码实现:
递归:(leetcode已经AC)
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
import java.util.ArrayList;
public class Solution {
ArrayList<Integer> out =new ArrayList<Integer>();
public ArrayList<Integer> preorderTraversal(TreeNode root) {
if(root==null){
return out;
}
out.add(root.val);
if(root.left!=null){
preorderTraversal(root.left);
}
if(root.right!=null){
preorderTraversal(root.right);
}
return out;
}
}
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
//深度优先搜索实现,Stack
import java.util.ArrayList;
import java.util.Stack;
public class Solution {
public ArrayList<Integer> preorderTraversal(TreeNode root) {
ArrayList<Integer> out=new ArrayList<Integer>();
if(root==null){
return out;
}
Stack<TreeNode> temp=new Stack<TreeNode>();
temp.add(root);
while(!temp.isEmpty()){
TreeNode cur=temp.pop();
out.add(cur.val);
if(cur.right!=null){
temp.add(cur.right);
}
if(cur.left!=null){
temp.add(cur.left);
}
}
return out;
}
}