首页 > 代码库 > [LeetCode]Binary Tree Preorder Traversal

[LeetCode]Binary Tree Preorder Traversal

题目:给定一颗二叉树,用非递归的前序遍历方法遍历这颗树

算法:

将根节点压入栈中
若栈非空,则执行循环
	取出栈顶二叉树节点
	访问节点
	压入节点的右孩子
	压入节点的左孩子

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
       /**
		 * Algorithm:
		 * 
		 * 1. push root into stack
		 * when stack is not empty
		 *     2. get node from stack
		 *     3. visit node
		 *     4. if null!=node.right then push node.right end
		 *     5. if null!=node.left then push node.left end
		 */
	    public List<Integer> preorderTraversal(TreeNode root) {
	        List<Integer> preorderList = new ArrayList<Integer>();
	        if (null == root) {
	    		// Empty tree
	    		return preorderList;
	    	}
	        
	        Stack<TreeNode> stack = new Stack<TreeNode>();
	        stack.add(root);
	        while (!stack.empty()) {
	        	TreeNode node = stack.pop();
	        	preorderList.add(node.val);
	        	
	        	if (null != node.right) {
	        		stack.add(node.right);
	        	}
	        	if (null != node.left) {
	        		stack.add(node.left);
	        	}
	        }
	        return preorderList;
	    }
}