给你一棵二叉树的根节点 root ,返回其节点值的 后序遍历 。
示例 1:
输入:root = [1,null,2,3]
输出:[3,2,1]
示例 2:
输入:root = []
输出:[]
示例 3:
输入:root = [1]
输出:[1]
提示:
树中节点的数目在范围 [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
| class Solution { List<Integer> list = new ArrayList<>(); public List<Integer> postorderTraversal(TreeNode root) { postorder02(root); return list; } public void postorder01(TreeNode root){ if(root==null) return; postorder01(root.left); postorder01(root.right); list.add(root.val); }
public void postorder02(TreeNode root){ if(root==null) return; Stack<TreeNode> st = new Stack<>(); TreeNode pre = null; while(root!=null||!st.isEmpty()){ while(root!=null){ st.push(root); root = root.left; } root = st.peek(); if(root.right != null && root.right != pre){ root = root.right; }else{ root = st.pop(); list.add(root.val); pre = root; root = null; } } }
public void postorder03(TreeNode root){ if(root==null) return; Stack<TreeNode> st = new Stack<>(); st.push(root); while(!st.isEmpty()){ TreeNode node = st.pop(); if(node!=null){ st.push(node); st.push(null); if(node.right!=null) st.push(node.right); if(node.left!=null) st.push(node.left); }else{ node = st.pop(); list.add(node.val); } } } }
|
后序遍历找根节点到叶子结点的所有路径
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
| class Solution { public List<List<Integer>> find_path(TreeNode root) { List<List<Integer>> ans = new ArrayList<>(); List<Integer> path = new ArrayList<>(); if(root==null) return list; Stack<TreeNode> st = new Stack<>(); TreeNode pre = null; while(root!=null||!st.isEmpty()){ while(root!=null){ st.push(root); root = root.left; } root = st.peek(); if(root.right==null||root.right==pre){ if(root.left==null&&root.right==null){ for(TreeNode node : st){ path.add(node.val) } ans.add(path); } root = st.pop(); pre = root; root = null; }else{ root = root.right; } } return ans; } }
|