PreOrder,InOrder,PostOrder traversal using Iterations

 //inOrder traversal....

public List<Integer> inorderTraversal(TreeNode root) {
         List<Integer> ans = new ArrayList<Integer>();
         Stack<TreeNode> st = new Stack<>();
         if(root==null)
         return ans;
         TreeNode node =root;
         while(true){
             if(node!=null){
                 st.push(node);
                 node=node.left;
             }else{
                 if(st.isEmpty())
                 break;
                 node=st.pop();
                 ans.add(node.val);
                 node=node.right;
             }
         }
         return ans;

//preOrder traversal below..

 public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> ans = new ArrayList<>();
        if(root==null)
        return ans;
        Stack<TreeNode> st = new Stack<>();
        st.push(root);
        while(!st.isEmpty()){
            TreeNode cur = st.pop();
            if(cur!=null && cur.right!=null) st.push(cur.right);
            if(cur!=null && cur.left!=null) st.push(cur.left);
            if(cur!=null)
            ans.add(cur.val);
        }
        return ans;
    }


//postOrder traversal below...

1>>using two stack..

ArrayList<Integer> postOrder(Node root) { // Your code goes here ArrayList<Integer> ans = new ArrayList<>(); Stack<Node> st1 = new Stack<>(); Stack<Node> st2 = new Stack<>(); if(root==null) return ans; st1.push(root); while(!st1.isEmpty()){ Node cur=st1.pop(); st2.push(cur); if(cur.left!=null) st1.push(cur.left); if(cur.right!=null) st1.push(cur.right); } while(!st2.isEmpty()){ ans.add(st2.pop().data); } return ans; }
2>> using two stack...

Comments