美文网首页
67. 二叉树的中序遍历

67. 二叉树的中序遍历

作者: 叨逼叨小马甲 | 来源:发表于2017-12-05 00:03 被阅读0次

给出一棵二叉树,返回其中序遍历
样例
给出二叉树 {1,#,2,3},

   1
    \
     2
    /
   3

返回 [1,3,2].

代码

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

import LintClass.TreeNode;

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */


public class InorderTraversal_67 {
    /*
     * @param root: A Tree
     * @return: Inorder in ArrayList which contains node values.
     */
    List<Integer> output = new ArrayList<Integer>();
    public List<Integer> inorderTraversal(TreeNode root) {
        // left, root, right
        TreeNode cur = root;
        
        if(cur == null)
            return output;
        
        if(cur.left != null) {
            inorderTraversal(cur.left);
        }
        
        output.add(cur.val);
        
        if(cur.right != null) {
            inorderTraversal(cur.right);
        }
        
        return output;
    }
    
    public static void main(String[] args) {
        TreeNode root = new TreeNode(1);
        TreeNode root_1_right = new TreeNode(2);
        TreeNode root_2_left = new TreeNode(3);
        root.right = root_1_right;
        root.right.left = root_2_left;
        InorderTraversal_67 obj = new InorderTraversal_67();
        System.out.print(obj.inorderTraversal(root));
    }
}

相关文章

网友评论

      本文标题:67. 二叉树的中序遍历

      本文链接:https://www.haomeiwen.com/subject/yjzfixtx.html