LeetCode non-recursive traversal of the tree to achieve (the first order and post-order)

One problem :
Postorder
Title Description
After seeking a given binary tree traversal sequence.
E.g:
Given binary {1, # 2, 3},
   1↵    ↵     2↵    /↵   3↵
Back [3,2,1].
Remarks; recursive solution to this question too is not new, and it can be given an iterative solution?
Given a binary tree, return the postorder traversal of its nodes' values.
For example:

Given binary tree{1,#,2,3},

   1↵    ↵     2↵    /↵   3↵

return[3,2,1].

Note: Recursive solution is trivial, could you do it iteratively?

 

Problem-solving ideas: about tree traversal, the first thought is recursive implementation, but the subject of the request does not use recursion;

  Stack data structure can be considered, go in after traversal, after coming in first traversal

  After the last note-order traversal need to flip it

import java.util.ArrayList;
import java.util.Stack;
import java.util.Collections;
/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */

public class Solution {
    public ArrayList<Integer> postorderTraversal(TreeNode root) {
        if(root == null){
            return new ArrayList<Integer>();
        }
        ArrayList<Integer> list = new ArrayList<Integer>();
        Stack<TreeNode> stack = new Stack<TreeNode>();
        stack.push(root);
        while(!stack.isEmpty()){
            TreeNode node = stack.pop();
            list.add(node.val);
            if(node.left != null){
                stack.push(node.left);
            }
            if(node.right != null){
                stack.push(node.right);
            }
        }
        Collections.reverse(list);
        return list;
    }
}

 

Question two:

Preorder,

Idea: using the same stack implementation

import java.util.ArrayList;
import java.util.Stack;
/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ArrayList<Integer> preorderTraversal(TreeNode root) {
        if(root == null){
            return new ArrayList<Integer>();
        }
        ArrayList<Integer> list = new ArrayList<Integer>();
        Stack<TreeNode> stack  = new Stack<TreeNode>();
        stack.push(root);
        while(!stack.isEmpty()){
            TreeNode node = stack.pop();
            list.add(node.val);
            if(node.right != null){
                stack.push(node.right);
            }
            if(node.left != null){
                stack.push(node.left);
            }
        }
        return list;
    }
}

Guess you like

Origin www.cnblogs.com/lc1475373861/p/12024762.html