二叉排序树 java 非递归

225 2024-02-28 19:36

java import java.util.Stack; class TreeNode { int val; TreeNode left; TreeNode right; public TreeNode(int val) { this.val = val; } } public class BST { public TreeNode insert(TreeNode root, int key) { if (root == null) { return new TreeNode(key); } TreeNode curr = root; while (true) { if (key < curr.val) { if (curr.left == null) { curr.left = new TreeNode(key); break; } else { curr = curr.left; } } else { if (curr.right == null) { curr.right = new TreeNode(key); break; } else { curr = curr.right; } } } return root; } public static void main(String[] args) { TreeNode root = null; BST bst = new BST(); root = bst.insert(root, 5); root = bst.insert(root, 3); root = bst.insert(root, 7); } }
顶一下
(0)
0%
踩一下
(0)
0%
相关评论
我要评论
点击我更换图片