最近发现面试很喜欢考二叉树的遍历,所以补一个。
树的节点结构:
public class TreeNode{
public int value;
public TreeNode left;
public TreeNode right;
public TreeNode(int data){
this.data = data;
}
}
一,二叉树的先序遍历
先序遍历顺序为根->左->右:
递归方法:
public void preOrderRecur(TreeNode root){
if(root == null){
return;
}
System.out.println(root.val + " ");
preOrderRecur(root.left);
preOrderRecur(root.right);
}
非递归方法:
二叉树遍历所有的方法都可以通过栈结构实现,其中先序遍历是先把根节点押入栈内,然后pop()并记录,然后压入当前节点的右节点和左节点,循环这一过程。
public List<Integer> preorderTraversal(TreeNode root){
List<Integer> list = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
TreeNode cur = root;
stack.push(cur);
while(cur != null || !stack.isEmpty()){
cur = stack.pop();
list.add(cur.val);
if(cur.right != null){
stack.push(cur.right);
}
if(cur.left != null){
stack.push(cur.left);
}
}
return list;
}
二,二叉树的中序遍历
中序遍历顺序为左->根->右
递归方法:
public void inorderRecur(TreeNode root){
if(root == null)
return;
inorderRecur(root.left);
System.out.println(root.val + " ");
inorderRecur(root.right);
}
中序遍历的非递归方法先把左节点压入栈中, 当左节点全部压入,记录当前节点,并从当前节点的右节点开始循环。
public List<Integer> InorderTraversal(TreeNode root){
List<Integer> list = new ArrayList<Integer>();
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode cur = root;
while(cur != null || !stack.isEmpty()){
while(cur != null){
stack.push(cur);
cur = cur.left;
}
cur = stack.pop();
list.add(cur.val);
cur = cur.right;
}
return list;
}
三,二叉树的后序遍历
后续遍历的顺序为:左->右->根
递归方法:
public void postorderRecur(TreeRoot root){
if(root == null)
return;
postorderRecur(root.left);
postorderRecur(root.right);
System.out.println(root.val + " ");
}
非递归方法:
需要用两个栈,我们先把根节点放到第一个栈中,第一个栈为辅助栈,为了调整节点顺序放到第二个栈中。循环开始时先pop(),然后放进第二个栈。然后把当前节点的左节点和右节点放进第一个栈。循环结束后,遍历第二个栈记录就好。
public List<Integer> postorderTraversal(TreeNode root){
List<Integer> list = new ArrayList<>();
Stack<TreeNode> stack1 = new Stack<>();
Stack<TreeNode> stack2 = new Stack<>();
TreeNode cur = root;
stack.push(cur);
while(!stack1.isEmpty()){
cur = stack1.pop();
stack2.push(cur);
if(cur.left != null)
stack1.push(cur.left);
if(cur.right != null)
stack1.push(cur.right);
}
while(!stack2.isEmpty()){
list.add(stack2.pop().val);
}
return list;
}