二叉树的先序遍历,递归实现:
public List preorderTraversal(TreeNode root)
{ //用栈来实现
List list = new ArrayList();
PreOrderTraversal(root,list);
return list;
}
public void PreOrderTraversal(TreeNode root,List list)
{
if(root == null)
return;
list.add(root.val);
if(root.left != null)
PreOrderTraversal(root.left,list);
if(root.right != null)
PreOrderTraversal(root.right,list);
}
二叉树先序遍历,非递归实现:
public static List PreOrderTree(TreeNode root)
{
List list = new ArrayList();
if(root == null)
return list;
Stack stack = new Stack<>();
TreeNode pCur = root;
while(pCur != null || !stack.isEmpty())
{
list.add(pCur.val);
stack.push(pCur);
pCur = pCur.left;
while(pCur == null && !stack.isEmpty())
{
pCur = stack.pop();
pCur = pCur.right;
}
}
return list;
}
二叉树中序遍历,递归实现:
public List inorderTraversal(TreeNode root)
{
Stack stack = new Stack();
List list = new ArrayList();
inOrderTraversal(root,stack,list);
return list;
}
public void inOrderTraversal(TreeNode root,Stack stack,List list)
{
if(root == null)
return;
stack.push(root); //先放根节点
if(root.left != null)
inOrderTraversal(root.left,stack,list); //先判断父节点的左子树是否为空
list.add(stack.pop().val); //左子树为空,那么就将父节点压出栈,保存进list中
if(root.right != null) //然后是遍历右子树
inOrderTraversal(root.right,stack,list);
}
二叉树的中序遍历,非递归实现:
public static List InOrderTree(TreeNode root)
{
List list = new ArrayList<>();
if(root == null)
return list;
Stack stack = new Stack<>();
TreeNode pCur = root;
while(pCur != null || !stack.isEmpty())
{
stack.push(pCur);
pCur = pCur.left;
while(pCur == null && !stack.isEmpty())
{
pCur = stack.peek().right;
list.add(stack.pop().val);
}
}
return list;
}
二叉树的后序遍历,非递归实现:
public static List PostOrderTree(TreeNode root)
{
List list = new ArrayList<>();
if(root == null)
return list;
Stack stack = new Stack<>();
Boolean flag = false; //判断该节点是否已经被遍历过
TreeNode pCur = root;
TreeNode temp = null;
while(pCur != null)
{
stack.add(pCur);
pCur = pCur.left;
if(pCur == null)
{
flag = true;
temp = null;
while(!stack.isEmpty() && flag == true)
{
pCur = stack.peek();
if(pCur.right == temp || pCur.right == null)
{
list.add(pCur.val);
temp = stack.pop();
}
else
{
pCur = pCur.right;
flag = false;
}
}
if(stack.isEmpty())
return list;
}
}
return list;
}
二叉树的层次遍历实现:
public ArrayList> levelOrder(Node root) //层次遍历
{
ArrayList> list = new ArrayList<>();
if(root == null)
return list;
Queue queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty())
{
int levelNum = queue.size();
ArrayList levelList = new ArrayList<>();
for(int i = 0; i < levelNum; i++)
{
Node temp = queue.poll();
levelList.add(temp.val);
if(temp.children != null)
for(Node ele : temp.children)
queue.add(ele);
}
list.add(levelList);
}
return list;
}