コード例 #1
0
        public BinaryTreeNode DeleteNode(BinaryTreeNode node, int val)
        {
            if (node == null || !node.val.HasValue)
            {
                return(null);
            }

            var value = node.val.Value;

            if (value == val)
            {
                // 删除

                // node为叶子节点  直接删除
                if (node.left == null && node.right == null)
                {
                    return(null);
                }

                // node为单子节点  子节点替代
                if (node.left == null || node.right == null)
                {
                    return(node.left ?? node.right);
                }

                var minNode = node.right;

                while (minNode.left != null)
                {
                    minNode = minNode.left;
                }

                var retNode = DeleteNode(node.right, minNode.val.Value);

                node.right = retNode;

                node.val = minNode.val.Value;

                // node为双子节点
                //BinaryTreeNode minNode = null;
                //DeleteMinNode(node.right, ref minNode);

                //if (minNode != null)
                //{
                //    minNode.left = node.left;
                //    minNode.right = node.right;
                //}

                //return minNode;
            }
            else if (val < value)
            {
                if (node.left != null)
                {
                    node.left = DeleteNode(node.left, val);
                }
            }
            else
            {
                if (node.right != null)
                {
                    node.right = DeleteNode(node.right, val);
                }
            }

            return(node);
        }
コード例 #2
0
 public BinaryTreeNode(int val, BinaryTreeNode left, BinaryTreeNode right)
 {
     this.val   = val;
     this.left  = left;
     this.right = right;
 }