题目描述:
给定一个二叉树,返回它的 前序 遍历。
示例:
输入: [1,null,2,3]
1
\
2
/
3
输出: [1,2,3]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-preorder-traversal
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
递归解法:
class Solution {
List<Integer> list = new ArrayList<>();
public List<Integer> preorderTraversal(TreeNode root) {
preorder(root);
return list;
}
private void preorder(TreeNode root) {
if(root != null){
list.add(root.val);
if(root.left != null){
preorder(root.left);
}
if(root.right != null){
preorder(root.right);
}
}
}
}
非递归遍历:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<>();
if(root != null){
Stack<TreeNode> st = new Stack<>();
st.push(root);
while (!st.empty()){
root = st.pop();
list.add(root.val);
if(root.right != null){
st.push(root.right);
}
if(root.left != null){
st.push(root.left);
}
}
}
return list;
}
}
莫里斯遍历:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<>();
TreeNode cur1 = root;
TreeNode cur2 = root;
while (cur1 != null) {
cur2 = cur1.left;
if (cur2 != null) {
while (cur2.right != null && cur2.right != cur1) {
cur2 = cur2.right;
}
if (cur2.right == null) {
cur2.right = cur1;
list.add(cur1.val);
cur1 = cur1.left;
continue;
} else {
cur2.right = null;
}
} else {
list.add(cur1.val);
}
cur1 = cur1.right;
}
return list;
}
}