题目:
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].
Note: Recursive solution is trivial, could you do it iteratively?
分析:
先根遍历二叉树,就是说,对二叉树中的每一个节点,先访问该节点,再访问其左子树,最后访问其右子树。用迭代的方式先根遍历二叉树,需要借助栈。具体步骤如下:
(1)将根结点入栈
(2)进入循环。先弹出栈顶元素,访问它,然后将该元素的右子树入栈,最后将该元素的左子树入栈。左子树后于右子树入栈保证了左子树先于右子树被访问。
代码:
package global;
public class TreeNode {
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int x) {
val = x;
}
@Override
public String toString() {
return "TreeNode [val=" + val + ", left=" + left + ", right=" + right
+ "]";
}
}
package leetcode144;
import global.TreeNode;
import java.util.LinkedList;
import java.util.List;
/**
* 先根遍历树的规则是这样的:对于遇到的每一个节点,先访问节点本身,然后是左子树根节点。
* @author liyuncong
*
*/
public class LeetCode144 {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> result = new LinkedList<Integer>();
if (root == null) {
return result;
}
LinkedList<TreeNode> stack = new LinkedList<TreeNode>();
stack.push(root);
while (!stack.isEmpty()) {
TreeNode top = stack.pop();
if (top != null) {
result.add(top.val);
stack.push(top.right);
stack.push(top.left);
}
}
return result;
}
}
时间: 2024-10-06 20:54:59