二叉树的迭代遍历以及递归遍历

二叉树的前序遍历(递归版):

public ArrayList<Integer> inOrder(TreeNode root ){
        ArrayList<Integer> result = new ArrayList<Integer>();
        if(root == null){
             return result;
        }
        result.add(root.val);
        inOrder(root.left);+
        inOrder(root.right);
        return result;
    }    

二叉树的中序遍历(递归版):

public ArrayList<Integer> inOrder(TreeNode root ){
        ArrayList<Integer> result = new ArrayList<Integer>();
        if(root == null){
             return result;
        }
        inOrder(root.left);
        result.add(root.val);
        inOrder(root.right);
        return result;
    }

二叉树的后续遍历(递归版):

public ArrayList<Integer> inOrder(TreeNode root ){
        ArrayList<Integer> result = new ArrayList<Integer>();
        if(root == null){
             return result;
        }
        inOrder(root.left);
        inOrder(root.right);
        result.add(root.val);
        return result;
    }

递归版总结:

其实就是添加节点的地方不同

前序遍历:添加节点就是在递归之前添加;

中序遍历:添加节点在左右节点递归之间;

后序遍历:添加节点是在左右节点递归之后;

二叉树的前序遍历(迭代版):

 
 
public ArrayList<Integer> preOrder(TreeNode root){
ArrayList<Integer> result= new ArrayList<Integer>();
Stack<TreeNode> stack = new Stack<TreeNode>();
if(root == null){
return result;
}
if(root != null){
stack.push(root);
result.add(root.val);
root=root.left;
}else{
root=stack.pop();
root=root.right;
}
return result;
}
 

二叉树中序遍历(迭代版):

public ArrayList<Integer> inOrder(TreeNode root){
        ArrayList<Integer> result = new ArrayList<Integer>();
        Stack<TreeNode> stack = new Stack<TreeNode>();
        if(root == null){
             return result;
        }
        while(root != null || !stack.isEmpty()){
            if(root != null){
                stack.push(root);
                root=root.left;
            }else{
                root= stack.pop();
                result.add(root.val);
                root= root.right;
            }
        }
        return result;
    }

二叉树后序遍历(迭代版):

最开始以为他很难,当你理解前两个之后,就会发现他跟前序遍历很像!

    public ArrayList<Integer> postTreeNode(TreeNode root){
        Stack<TreeNode> midstack = new Stack<TreeNode>();
        Stack<TreeNode> resultstack= new Stack<TreeNode>() ;
        ArrayList<Integer> result = new ArrayList<Integer>();
        while(root != null || !midstack.isEmpty()){
            if(root != null){
                midstack.push(root);
                resultstack.push(root);
                root=root.right;
            }else{
                root=midstack.pop();
                root=root.left;
            }
        }
        while(resultstack.size() > 0){
            TreeNode temp = resultstack.pop();
            result.add(temp.val);
        }
        return result;
    }

猜你喜欢

转载自www.cnblogs.com/frank9571/p/11963441.html