94. Binary Tree Inorder Traversal(非递归实现二叉树的中序遍历)

太过爱你忘了你带给我的痛 2022-01-10 04:21 223阅读 0赞

Given a binary tree, return the inorder traversal of its nodes’ values.

Example:

  1. Input: [1,null,2,3]
  2. 1
  3. \
  4. 2
  5. /
  6. 3
  7. Output: [1,3,2]

Follow up: Recursive solution is trivial, could you do it iteratively?

方法一:递归

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode(int x) { val = x; }
  8. * }
  9. */
  10. class Solution {
  11. public void preorderTraversal(TreeNode root) {
  12. if(root==null) return ;
  13. preorderTraversal(root.left);
  14. System.out.print(root.val+' ');
  15. preorderTraversal(root.right);
  16. }
  17. }

方法二:迭代

中序遍历第左右根,所以设计程序时首先要考虑的是找到最左边的叶子结点。找到之后弹出还要考虑这个结点有没有右孩子。

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode(int x) { val = x; }
  8. * }
  9. */
  10. class Solution {
  11. public List<Integer> inorderTraversal(TreeNode root) {
  12. Stack<TreeNode> stack=new Stack<TreeNode>();
  13. List<Integer> list=new ArrayList<Integer>();
  14. while (root!=null||!stack.isEmpty()){
  15. while (root!=null){
  16. stack.add(root);
  17. root=root.left;
  18. }
  19. TreeNode treeNode=stack.pop();
  20. list.add(treeNode.val);
  21. root=treeNode.right; //root是判断条件。每次弹出的结点都要检查是否还有右孩子。有就加入,没有就弹出。
  22. }
  23. return list;
  24. }
  25. }

转载于:https://www.cnblogs.com/shaer/p/10670452.html

发表评论

表情:
评论列表 (有 0 条评论,223人围观)

还没有评论,来说两句吧...

相关阅读