leetcode_二叉树的前序,中序,后序遍历实现

leetcode_二叉树的前序,中序,后序遍历实现

 

前序遍历

https://leetcode-cn.com/problems/binary-tree-preorder-traversal/

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List preorderTraversal(TreeNode root) {
                LinkedList stack=new LinkedList<>();
        LinkedList out=new LinkedList<>();
         if(root==null){
             return out;
         }
         stack.add(root);
         while(!stack.isEmpty()){
            TreeNode last = stack.pollLast();
            out.add(last.val);
            if(last.right!=null){
                stack.add(last.right);
            }
             if(last.left!=null){
                stack.add(last.left);
            }
         }
         return out;
    }
}

 

中序遍历

https://leetcode-cn.com/problems/binary-tree-inorder-traversal/

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List inorderTraversal(TreeNode root) {
            Stack stack=new Stack<>();
            LinkedList out=new LinkedList<>();
            TreeNode curr=root;
            while(!stack.isEmpty()|| curr !=null){
                while(curr!=null){
                    stack.push(curr);
                    curr=curr.left;
                }
                curr=stack.pop();
                out.add(curr.val);
                curr=curr.right;
            }
            return out;
    }
}

 

后序遍历

https://leetcode-cn.com/problems/binary-tree-postorder-traversal/

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List postorderTraversal(TreeNode root) {
        LinkedList stack=new LinkedList<>();
         LinkedList out=new LinkedList<>();
         if(root==null){
             return out;
         }
         stack.add(root);
         while(!stack.isEmpty()){
            TreeNode last=stack.pollLast();
             out.addFirst(last.val);
             if(last.left!=null){
                stack.add(last.left); 
             }
             if(last.right!=null){
                stack.add(last.right); 
             }
         }
         return out;
    }
}

 

你可能感兴趣的:(leetcode_二叉树的前序,中序,后序遍历实现)