鱼C论坛

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

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

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

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

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

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

Example:

Input: [1,null,2,3]
   1
    \
     2
    /
   3

Output: [1,3,2]
Follow up: Recursive solution is trivial, could you do it iteratively?
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<Integer>();
        if(root == null) return list;
        help(root,list);
        return list;
        
    }
    public void help(TreeNode root, List<Integer> list){
        if(root == null) return;
        
        if(root.left == null && root.right == null){
            list.add(root.val);
        }
        else if(root.left != null && root.right == null) {
            
            help(root.left, list);
            list.add(root.val);
        }
        else if(root.right != null && root.left == null){
            list.add(root.val);
            help(root.right,list);
        }
        else{
            
            help(root.left,list);
            list.add(root.val);
            help(root.right,list);
        }
}
}
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<Integer>();
        
        Stack <TreeNode> stack = new Stack<>();
        TreeNode c = root;
        while(c != null || !stack.isEmpty()){
            while(c != null){
                
                stack.push(c);
                c = c.left;
            }
            c = stack.pop();
            list.add(c.val);
            c = c.right;
        }
        return list;
        
    }

}

本帖被以下淘专辑推荐:

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

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

本版积分规则

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

GMT+8, 2024-9-28 22:53

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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