描述
给出一棵二叉树,返回其节点值的前序遍历。
样例
给出一棵二叉树 {1,#,2,3},
1
\
2
/
3
返回 [1,2,3].
挑战
你能使用非递归实现么?
前序
根左右
代码
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
- 非递归+栈(重点)
PS:
注意区分stack.isEmpty()和stack == null
public class Solution {
/**
* @param root: The root of binary tree.
* @return: Preorder in ArrayList which contains node values.
*/
public List<Integer> preorderTraversal(TreeNode root) {
Stack<TreeNode> stack = new Stack<TreeNode>();
List<Integer> preorder = new ArrayList<>();
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;
}
}
- 遍历+递归
public class Solution {
/**
* @param root: The root of binary tree.
* @return: Preorder in ArrayList which contains node values.
*/
public ArrayList<Integer> preorderTraversal(TreeNode root) {
ArrayList<Integer> result = new ArrayList<Integer>();
traverse(root, result);
return result;
}
private void traverse(TreeNode root, ArrayList<Integer> result) {
if (root == null) {
return;
// return;表示不做任何操作
}
result.add(root.val);
traverse(root.left, result);
traverse(root.right, result);
}
}
- 分治+递归
public class Solution {
/**
* @param root: The root of binary tree.
* @return: Preorder in ArrayList which contains node values.
*/
public ArrayList<Integer> preorderTraversal(TreeNode root) {
ArrayList<Integer> result = new ArrayList<Integer>();
if (root == null) {
return result;
}
ArrayList left = preorderTraversal(root.left);
ArrayList right = preorderTraversal(root.right);
result.add(root.val);
result.addAll(left);
result.addAll(right);
// 三行代码的添加顺序不能变,即前序遍历的根左右
return result;
}
}
关于ArrayList.addAll():
result.addAll(list); // 把list中的每一个元素加到result中,
result.size()==list.size()
result.add(list); // 将list作为一个元素加到result中,则
result.size()为1
在使用ArrayList的addAll()方法的时候一定要进行list非null的判断