145. Binary Tree Postorder Traversal

题目[Binary Tree Postorder Traversal](145. Binary Tree Postorder Traversal)

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?

1,递归
public List postorderTraversal(TreeNode root) {
        List result = new ArrayList();
        dfs(root,result);
        return result;
    }
    
    private void dfs(TreeNode root, List result){
        if(root == null){
            return;
        }
        dfs(root.left,result);
        dfs(root.right,result);
        result.add(root.val);
    }
2,非递归一
public List postorderTraversal(TreeNode root) {
        LinkedList result = new LinkedList();
        if(root == null){
            return result;
        }
        Stack stack = new Stack();
        stack.push(root);
        while(!stack.empty()){
            TreeNode node = stack.pop();
            result.addFirst(node.val);
            if(node.left != null){
                stack.push(node.left);
            }
            
            if(node.right != null){
                stack.push(node.right);
            }
        }
        
        return result;
     }
3,非递归二
public List postorderTraversal(TreeNode root) {
        LinkedList result = new LinkedList();
        if(root == null){
            return result;
        }
        
        Stack stack = new Stack();
        TreeNode node = root;
        TreeNode tempNode = null;
        boolean visited = false;
        int height = 0;
        do{
            while(node != null ){
                stack.push(node);
                node = node.left;
            }
            
            tempNode = null;
            visited = true;
            while(!stack.empty() && visited){
                node = stack.peek();
                if(node.right == tempNode){
                    result.add(node.val);
                    tempNode = node;
                    stack.pop();
                }else{
                    node = node.right;
                    visited = false;
                }
            }
        }while(!stack.empty());
        return result;
        
    }

你可能感兴趣的:(145. Binary Tree Postorder Traversal)