本文主要是介绍LeetCode_145(二叉树的后序遍历),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1.递归
public List<Integer> postorderTraversal(TreeNode root) {List<Integer> res = new ArrayList<>();accessTree(root,res);return res;}public void accessTree(TreeNode root, List<Integer> res){if(root == null){return;}accessTree(root.left,res);accessTree(root.right,res);res.add(root.val);}
2.循环迭代
public List<Integer> postorderTraversal(TreeNode root) {List<Integer> res = new ArrayList<>();Deque<TreeNode> stack = new LinkedList<>();TreeNode prevAccess = null;while( root!=null || !stack.isEmpty() ){while (root !=null){stack.push(root);root = root.left;}root = stack.pop();if(root.right == null || root.right == prevAccess){res.add(root.val);prevAccess = root;root = null;}else{stack.push(root);root = root.right;}}return res;}
这篇关于LeetCode_145(二叉树的后序遍历)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!