二叉树常见遍历方式与题目总结
二叉树常见遍历方式
树的定义
/**
\* Definition for a binary tree node.
\* public class TreeNode {
\* int val;
\* TreeNode left;
\* TreeNode right;
\* TreeNode(int x) { val = x; }
\* }
*/
(1)前序遍历
先访问根节点,然后前序遍历左子树,再前序遍历右子树
(a) 递归的方法遍历
void preoder(TreeNode T)
{
if(T==null) return ;
sysytem.out。print(T.val);
preoder(TreeNode T.left);
preoder(TreeNode T.right);
}
(b)非递归
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
LinkedList<TreeNode> stack = new LinkedList<>();
LinkedList<Integer> output = new LinkedList<>();
if (root == null) {
return output;
}
stack.add(root);
while (!stack.isEmpty()) {
TreeNode node = stack.pollLast();
output.add(node.val);
if (node.right != null) {
stack.add(node.right);
}
if (node.left != null) {
stack.add(node.left);
}
}
return output;
}
}
(2)中序遍历
(a)递归
void preoder(TreeNode T)
{
if(T==null) return ;
preoder(TreeNode T.left);
sysytem.out.print(T.val);
preoder(TreeNode T.right);
}
(b) 非递归
public void inOrder() {
Node current = root;
//把LinkedList作为栈使用
LinkedList<Node> s = new LinkedList<Node>();
while (current != null || !s.isEmpty()) {
while (current != null) {
s.addFirst(current);
current = current.left;
}
if (!s.isEmpty()) {
current = s.removeFirst();
System.out.print(current.data + " -> ");
current = current.right;
}
}
}
(3)后序遍历
(a) 递归
public static void postOrderRecur(TreeNode head) {
if (head == null) {
return;
}
postOrderRecur(head.left);
postOrderRecur(head.right);
System.out.print(head.value + " ");
}
(b)非递归
public static void postOrderIteration(TreeNode head) {
if (head == null) {
return;
}
Stack<TreeNode> stack1 = new Stack<>();
Stack<TreeNode> stack2 = new Stack<>();
stack1.push(head);
while (!stack1.isEmpty()) {
TreeNode node = stack1.pop();
stack2.push(node);
if (node.left != null) {
stack1.push(node.left);
}
if (node.right != null) {
stack1.push(node.right);
}
}
while (!stack2.isEmpty()) {
System.out.print(stack2.pop().value + " ");
}
}
if (node.right != null) {
stack1.push(node.right);
}
}
while (!stack2.isEmpty()) {
System.out.print(stack2.pop().value + " ");
}
}