您的位置:首页 > 其它

树的遍历(前序,中序,后续,栈与递归实现)

2017-07-24 21:50 281 查看

树的定义

public class TreeNode {
public TreeNode left;
public TreeNode right;
public int val;
public TreeNode(int val){
this.val=val;
this.left=null;
this.right=null;
}
}

前序遍历

public void preorderStack(TreeNode root) {
Stack<TreeNode> stack=new Stack<>();
while(root!=null || !stack.isEmpty()){
while(root!=null){
stack.push(root);
System.out.println(root.val);
root=root.left;
}
root=stack.pop();
root=root.right;
}
}
public void preOrder(TreeNode root){
if(root!=null){
System.out.println(root.val);
preOrder(root.left);
preOrder(root.right);
}
}



中序遍历

public void inorderStack(TreeNode root) {
Stack<TreeNode> stack=new Stack<>();
while(root!=null || !stack.isEmpty()){
while(root!=null){
stack.push(root);
root=root.left;
}
root=stack.pop();
System.out.println(root.val);
root=root.right;
}
}
public void inOrder(TreeNode root){
if(root!=null){

inOrder(root.left);
System.out.println(root.val);
inOrder(root.right);
}
}

后序遍历

public void  postorderStack(TreeNode root){
Stack<TreeNode>stack=new Stack<>();
Map<TreeNode, Boolean> map=new HashMap<>();
stack.push(root);
while(!stack.isEmpty()){
TreeNode node=stack.peek();
if(node.left!=null && !map.containsKey(node.left)){
node=node.left;
while(node!=null){
if(map.containsKey(node))break;
stack.push(node);
node=node.left;
}
continue;
}
if(node.right!=null && !map.containsKey(node.right)){
stack.push(node.right);
continue;
}
TreeNode t=stack.pop();
map.put(t, true);
System.out.println(t.val);
}
}
public void postOrder(TreeNode root){
if(root!=null){
postOrder(root.left);
postOrder(root.right);
System.out.println(root.val);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐