鱼C论坛

 找回密码
 立即注册
查看: 2381|回复: 0

[学习笔记] leetcode 94. Binary Tree Inorder Traversal

[复制链接]
发表于 2019-9-22 08:24:05 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
  1. Given a binary tree, return the inorder traversal of its nodes' values.

  2. Example:

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

  9. Output: [1,3,2]
  10. 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 List<Integer> inorderTraversal(TreeNode root) {
  12.         List<Integer> list = new ArrayList<Integer>();
  13.         if(root == null) return list;
  14.         help(root,list);
  15.         return list;
  16.         
  17.     }
  18.     public void help(TreeNode root, List<Integer> list){
  19.         if(root == null) return;
  20.         
  21.         if(root.left == null && root.right == null){
  22.             list.add(root.val);
  23.         }
  24.         else if(root.left != null && root.right == null) {
  25.             
  26.             help(root.left, list);
  27.             list.add(root.val);
  28.         }
  29.         else if(root.right != null && root.left == null){
  30.             list.add(root.val);
  31.             help(root.right,list);
  32.         }
  33.         else{
  34.             
  35.             help(root.left,list);
  36.             list.add(root.val);
  37.             help(root.right,list);
  38.         }
  39. }
  40. }
复制代码

  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.         List<Integer> list = new ArrayList<Integer>();
  13.         
  14.         Stack <TreeNode> stack = new Stack<>();
  15.         TreeNode c = root;
  16.         while(c != null || !stack.isEmpty()){
  17.             while(c != null){
  18.                
  19.                 stack.push(c);
  20.                 c = c.left;
  21.             }
  22.             c = stack.pop();
  23.             list.add(c.val);
  24.             c = c.right;
  25.         }
  26.         return list;
  27.         
  28.     }

  29. }
复制代码

本帖被以下淘专辑推荐:

小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-5-13 20:48

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表