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<Integer> preorderTraversal(TreeNode root) { LinkedList<TreeNode> stack=new LinkedList<>(); LinkedList<Integer> 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<Integer> inorderTraversal(TreeNode root) { Stack<TreeNode> stack=new Stack<>(); LinkedList<Integer> 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<Integer> postorderTraversal(TreeNode root) { LinkedList<TreeNode> stack=new LinkedList<>(); LinkedList<Integer> 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; } }