二叉树遍历(前序、中序、后序、层次、深度优先、广度优先遍历)
描述
解析
递归方案
很简单,先左孩子,输出根,再右孩子。
非递归方案
因为访问左孩子后要访问右孩子,所以需要栈这样的数据结构。
1.指针指向根,根入栈,指针指向左孩子。把左孩子当作子树的根,继续前面的操作。
2.如果某个节点的左孩子不存在,节点出栈,指针指向节点的右孩子。把这个右节点当作根, 继续前面的操作。
代码
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { List<Integer> list = new ArrayList<>(); public List<Integer> inorderTraversal(TreeNode root) { if (null == root) { return list; } inorderTraversal(root.left); list.add(root.val); inorderTraversal(root.right); return list; } }
/** * 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) { List<Integer> list = new ArrayList<>(); if (null == root) { return list; } Stack<TreeNode> stack = new Stack<>(); TreeNode curNode = root; while (null != curNode || !stack.isEmpty()) { if (null != curNode) { stack.push(curNode); curNode = curNode.left; } else { curNode = stack.pop(); list.add(curNode.val); curNode = curNode.right; } } return list; } }
/** * 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) { List<Integer> list = new ArrayList<>(); if (null == root) { return list; } Stack<TreeNode> stack = new Stack<>(); TreeNode curNode = root; while (curNode != null || !stack.isEmpty()) { while (curNode != null) { // Travel to each node's left child, till reach the left leaf stack.push(curNode); curNode = curNode.left; } curNode = stack.pop(); // Backtrack to higher level node A list.add(curNode.val); // Add the node to the result list curNode = curNode.right; // Switch to A'right branch } return list; } }