0.
二叉树是常见的数据结构,二叉树常见的遍历方式有前序遍历,中序遍历和后序遍历。前序遍历就是中-左-右节点的顺序,中序遍历就是左-中-右节点的顺序,后序遍历就是左-右-中节点的顺序。这三种遍历最常见的实践方式就是利用递归了,但是大家都明白,递归其实是可以用循环来代替的,所以除了递归的方式,还要循环的方法,同时递归还可以理解为栈的入栈和出栈的过程,配合循环,就可以实现相应的非递归遍历。
1.
由于实在太过简单,不说了,直接上代码:
<pre class="prettyprint linenums prettyprinted" style="box-sizing: border-box; margin: 0px; padding: 8px 0px 6px; font-family: consolas, menlo, courier, monospace, "Microsoft Yahei" !important; background: rgb(241, 239, 238); border: 1px solid rgb(226, 226, 226) !important; display: block; border-radius: 0px; overflow-y: auto; color: rgb(80, 97, 109); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 300; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial; font-size: 10px; line-height: 12px;">
-
//前序递归遍历
-
private void perorder(TreeNode treeNode)
-
{
-
if(treeNode!=null)
-
{
-
System.out.println("node is "+treeNode.val);
-
perorder(treeNode.left);
-
perorder(treeNode.right);
-
}
-
}
-
//前序非递归遍历
-
private void perorder(Stack<TreeNode> stack, TreeNode treeNode)
-
{
-
if(treeNode==null)
-
{
-
return;
-
}
-
TreeNode temp=treeNode;
-
while(temp!=null)
-
{
-
System.out.println("node is "+temp.val);
-
if(temp.right!=null)
-
{
-
stack.push(temp.right);
-
}
-
if(temp.left!=null)
-
{
-
stack.push(temp.left);
-
}
-
if(stack.empty())
-
{
-
break;
-
}
-
temp=stack.peek();
-
stack.pop();
-
}
-
}
-
//中序递归遍历
-
private void midorder(TreeNode treeNode)
-
{
-
if(treeNode!=null)
-
{
-
midorder(treeNode.left);
-
System.out.println("node is "+treeNode.val);
-
midorder(treeNode.right);
-
}
-
}
-
//中序非递归遍历
-
private void midorder(Stack<TreeNode> stack,TreeNode treeNode)
-
{
-
if(treeNode==null)
-
{
-
return;
-
}
-
TreeNode temp=treeNode;
-
while(!stack.empty() || temp!=null)
-
{
-
if(temp!=null)
-
{
-
stack.push(temp);
-
temp=temp.left;
-
}
-
else
-
{
-
temp=stack.pop();
-
System.out.println("node is "+temp.val);
-
temp=temp.right;
-
}
-
}
-
}
-
//后序递归遍历
-
private void endorder(TreeNode treeNode)
-
{
-
if(treeNode!=null)
-
{
-
endorder(treeNode.left);
-
endorder(treeNode.right);
-
System.out.println("node is "+treeNode.val);
-
}
-
}
-
//后序非递归遍历
-
private void endorder(Stack<TreeNode> stack,TreeNode treeNode)
-
{
-
if(treeNode==null)
-
{
-
return;
-
}
-
TreeNode temp=treeNode;
-
stack.push(treeNode);
-
while(!stack.empty())
-
{
-
TreeNode cur=stack.peek();
-
if(cur.left!=null && temp!=cur.left && temp!=cur.right)
-
{
-
stack.push(cur.left);
-
}
-
else if(cur.right!=null && temp!=cur.right)
-
{
-
stack.push(cur.right);
-
}
-
else
-
{
-
System.out.println("node is "+cur.val);
-
stack.pop();
-
temp=cur;
-
}
-
}
-
}
-
public static class TreeNode
-
{
-
int val;
-
TreeNode left;
-
TreeNode right;
-
public TreeNode(int val)
-
{
-
this.val=val;
-
}
-
}
</pre>
image关注我的公众号
网友评论