zoukankan      html  css  js  c++  java
  • 94. Binary Tree Inorder Traversal

    该题目是要将树进行中序遍历。理解了中序遍历的原理,就知道如何解答这一题目了。中序遍历就是首先遍历先遍历左节点,然后根节点,最后右节点。

    代码如下:

     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> res = new ArrayList<Integer>();
    13         
    14         if(root == null){
    15             return res;
    16         }
    17         
    18         helper(root, res);
    19         
    20         return res;
    21     }
    22     
    23     private void helper(TreeNode root, List<Integer> res ){
    24         
    25         if(root.left != null){
    26             helper(root.left, res);
    27         }
    28         
    29         res.add(root.val);
    30         
    31         if(root.right != null){
    32             helper(root.right, res);
    33         }
    34     }
    35 }

    END

  • 相关阅读:
    系统测试的策略
    POJ1611(并查集)
    POJ2752(KMP)
    POJ3176(DP)
    HDU2579(BFS)
    HDOJ1175(BFS)
    HDOJ1242(BFS)
    HDOJ1180(BFS)
    HDOJ1372(BFS)
    HDOJ2717(BFS)
  • 原文地址:https://www.cnblogs.com/sssysukww/p/8742907.html
Copyright © 2011-2022 走看看