给你二叉树的根节点 root ,返回它节点值的 前序 遍历。
示例 1:
输入:root = [1,null,2,3]
输出:[1,2,3]
示例 2:
输入:root = []
输出:[]
示例 3:
输入:root = [1]
输出:[1]
示例 4:
输入:root = [1,2]
输出:[1,2]
示例 5:
输入:root = [1,null,2]
输出:[1,2]
提示:
树中节点数目在范围 [0, 100] 内
-100 <= Node.val <= 100
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
| class Solution { List<Integer> list = new ArrayList<>(); public List<Integer> preorderTraversal(TreeNode root) { preorder03(root); return list; }
public void preorder01(TreeNode root){ if(root==null) return; list.add(root.val); preorder01(root.left); preorder01(root.right); }
public void preorder02(TreeNode root){ if(root==null) return; Stack<TreeNode> st = new Stack<>(); while(root!=null||!st.isEmpty()){ while(root!=null){ list.add(root.val); st.push(root); root = root.left; } TreeNode node = st.pop(); if(node.right != null){ root = node.right; } } }
public void preorder03(TreeNode root){ if(root==null) return; Stack<TreeNode> st = new Stack<>(); st.push(root); while(!st.isEmpty()){ root = st.pop(); list.add(root.val); if(root.right!=null){ st.push(root.right); } if(root.left!=null){ st.push(root.left); } } }
public void preorder04(TreeNode root){ if(root==null) return; Stack<TreeNode> st = new Stack<>(); st.push(root); while(!st.isEmpty()){ root = st.pop(); if(root!=null){ if(root.right!=null) st.push(root.right); if(root.left!=null) st.push(root.left); st.push(root); st.push(null); }else{ root = st.pop(); list.add(root.val); } } } }
|