鼠扑 发表于 7 天前

【无标题】

记载

2025.4.19
标题:

https://i-blog.csdnimg.cn/direct/00dc63cf9f414105baf050ef617c2fc8.png
思路:

按照访问左子树——根节点——右子树的方式遍历这棵树
解题步调:

界说 inorder(root) 表示当前遍历到 root 节点的答案,那么按照界说,我们只要递归调用 inorder(root.left) 来遍历 root 节点的左子树,然后将 root 节点的值加入答案,再递归调用inorder(root.right) 来遍历 root 节点的右子树即可,递归终止的条件为遇到空节点。
代码:

/**
* Definition for a binary tree node.
* public class TreeNode {
*   int val;
*   TreeNode left;
*   TreeNode right;
*   TreeNode() {}
*   TreeNode(int val) { this.val = val; }
*   TreeNode(int val, TreeNode left, TreeNode right) {
*         this.val = val;
*         this.left = left;
*         this.right = right;
*   }
* }
*/
class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
      List<Integer> res = new ArrayList<Integer>();
      inorder(root, res);
      return res;
    }

    public void inorder(TreeNode root, List<Integer> res) {
      if (root == null) {
            return;
      }
      inorder(root.left, res);
      res.add(root.val);
      inorder(root.right, res);
    }
}


复杂度:

N(N)
N(N)

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页: [1]
查看完整版本: 【无标题】