1:前序遍历(根,左,右)
递归的方法很简单:
public static void pr(TreeNode root){ if(root!=null){ System.out.println(root.val); pr(root.left); pr(root.right); } }
非递归的方法:可以借助栈,入栈的顺序分别为右,左,根。
代码如下:
public List<Integer> preorderTraversal(TreeNode root) { List<Integer> ls = new ArrayList<Integer>(); if (root == null) { return ls; } Stack<TreeNode> st = new Stack<TreeNode>(); st.push(root); while (!st.isEmpty()) { TreeNode temp = st.pop(); ls.add(temp.val); if (temp.right != null) { st.push(temp.right); } if (temp.left != null) { st.push(temp.left); } } return ls; }
2:中序遍历(左,根,右)
递归的方法:
public static void m(TreeNode root){ if(root!=null){ m(root.left); System.out.println(root.val); m(root.right); } }
非递归的方法:
首先要非常明白中序遍历一定是最先访问最左的结点,用栈来帮助实现。要访问某个结点,那在这个结点入栈之前一定将它所有的左子树结点全部入栈,然后每出栈一个节点将这个结点的有节点进栈,因为这个右子树也有可能有左子树,下面附上代码:
public List<Integer> inorderTraversal(TreeNode root) { Stack<TreeNode> st = new Stack<TreeNode>(); List<Integer> result = new ArrayList<Integer>(); TreeNode cur = root; while(cur!=null||!st.empty()){ while(cur!=null){ st.push(cur); cur = cur.left; } cur = st.pop(); result.add(cur.val); cur = cur.right; } return result; }
3:后序遍历(左右根)
递归的方法,代码如下:
public ArrayList<Integer> postorderTraversal(TreeNode root) { ArrayList<Integer> result = new ArrayList<Integer>(); if (root == null) { return result; } result.addAll(postorderTraversal(root.left)); result.addAll(postorderTraversal(root.right)); result.add(root.val); return result; }
非递归的方法,也是借助栈来完成,此时入栈的顺序为根,右,左。代码如下:
public List<Integer> postorderTraversal(TreeNode root) { ArrayList<Integer> result = new ArrayList<Integer>(); Stack<TreeNode> stack = new Stack<TreeNode>(); TreeNode prev = null; // previously traversed node TreeNode curr = root; if (root == null) { return result; } stack.push(root); while (!stack.empty()) { curr = stack.peek(); if (prev == null || prev.left == curr || prev.right == curr) { if (curr.left != null) { stack.push(curr.left); } else if (curr.right != null) { stack.push(curr.right); } } else if (curr.left == prev) { // traverse up the tree from the // left if (curr.right != null) { stack.push(curr.right); } } else { // traverse up the tree from the right result.add(curr.val); stack.pop(); } prev = curr; } return result; }
可参考网址:http://www.tuicool.com/articles/Yz2QJn
http://blog.csdn.net/kerryfish/article/details/24309617
时间: 2024-10-14 05:07:47