1. 树的前序遍历可以用栈来实现。方法如下:
(1)先访问当前节点的值。
(2)访问当前节点的右节点,如果不为空,将其压入栈中。
(3)访问当前节点的左节点,如果不为空,将其压入栈中。
(4)迭代实现。
1 //前序遍历的顺序节点存放在list中 2 public List<TreeNode> preorderUsingStack(TreeNode root) { 3 List<TreeNode> list = new LinkedList<TreeNode>(); 4 if (root == null) { 5 return list; 6 } 7 Stack<TreeNode> stack = new Stack<TreeNode>(); 8 stack.push(root); 9 while (!stack.isEmpty()) { 10 TreeNode tempNode = stack.pop(); 11 //先存入当前节点 12 list.add(tempNode); 13 //注意是先压栈右子节点再压栈左子节点 14 if (tempNode.right != null) { 15 stack.push(tempNode.right); 16 } 17 if (tempNode.left != null) { 18 stack.push(tempNode.left); 19 } 20 } 21 return list; 22 }
原文:http://www.cnblogs.com/choumeng/p/6279801.html