码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode]Binary Tree Preorder Traversal

时间:2014-07-16 09:08:19      阅读:257      评论:0      收藏:0      [点我收藏+]

标签:java   for   io   算法   re   new   

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

算法:

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

/**
 * 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;
	    }
}


[LeetCode]Binary Tree Preorder Traversal,布布扣,bubuko.com

[LeetCode]Binary Tree Preorder Traversal

标签:java   for   io   算法   re   new   

原文地址:http://blog.csdn.net/yeweiouyang/article/details/37813841

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!