标签:
Given a binary tree, return the preorder traversal of its nodes‘ values.
For example:
Given binary tree {1,#,2,3}
,
1 2 / 3
return [1,2,3]
.
二叉树的前序遍历,非递归的写法考的比较多,方法很简单,就是把跟节点加进来,依次把右子树和左子树压入栈内,弹出的时候肯定是先弹出左子树,然后再弹出右子树,
达到先遍历跟节点,再依次遍历左子树和右子树。
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public List<Integer> preorderTraversal(TreeNode root) { Stack<TreeNode> stack = new Stack<TreeNode>(); List<Integer> preorder = new ArrayList<Integer>(); if (root == null) { return preorder; } stack.push(root); while (!stack.empty()) { TreeNode node = stack.pop(); preorder.add(node.val); if (node.right != null) { stack.push(node.right); } if (node.left != null) { stack.push(node.left); } } return preorder; } }
leetcode 144. Binary Tree Preorder Traversal
标签:
原文地址:http://www.cnblogs.com/iwangzheng/p/5766144.html