标签:poll lis rsa class integer return while arraylist int
一、二叉树
非递归前序遍历
class Solution { public List<Integer> preorderTraversal(TreeNode root) { List<Integer> res = new ArrayList<>(); if(root == null) return res; Stack<TreeNode> st = new Stack<>(); st.push(root); while(!st.empty()){ TreeNode node = st.pop(); res.add(node.val); if(node.right != null) st.push(node.right); if(node.left != null) st.push(node.left); } return res; } }
非递归中序遍历
class Solution { public List<Integer> inorderTraversal(TreeNode root) { List<Integer> res = new ArrayList<>(); if(root == null) return res; Stack<TreeNode> st = new Stack<>(); TreeNode cur = root; while(!st.empty() || cur != null) { while(cur != null){ st.push(cur); cur = cur.left; } cur = st.pop(); res.add(cur.val); cur = cur.right; } return res; } }
非递归后序遍历
class Solution { public List<Integer> postorderTraversal(TreeNode root) { List<Integer> res = new LinkedList<>(); if(root == null) return res; Stack<TreeNode> st = new Stack<>(); st.push(root); while(!st.isEmpty()){ TreeNode node = st.pop(); res.add(0,node.val); if (node.left != null) st.push(node.left); if (node.right != null) st.push(node.right); } return res; } }
队列层次遍历
class Solution { public List<List<Integer>> levelOrder(TreeNode root) { List<List<Integer>> res = new ArrayList<>(); Queue<TreeNode> queue = new LinkedList<>(); if(root == null) return res; queue.add(root); while(!queue.isEmpty()){ List<Integer> list = new LinkedList<>(); int size = queue.size(); while(size-- > 0){ TreeNode node = queue.poll(); list.add(node.val); if(node.left!=null) queue.add(node.left); if(node.right!=null) queue.add(node.right); } res.add(list); } return res; } }
N叉树
标签:poll lis rsa class integer return while arraylist int
原文地址:https://www.cnblogs.com/Roni-i/p/10509883.html